21.7 C
Canberra
Tuesday, October 21, 2025

Optimizing queries by utilizing observability



Code snippet: Tracing PostgreSQL queries with OpenTelemetry (Python)

from opentelemetry import hint
from opentelemetry.instrumentation.psycopg2 import Psycopg2Instrumentor
from opentelemetry.sdk.hint import TracerProvider
from opentelemetry.sdk.hint.export import BatchSpanProcessor, ConsoleSpanExporter

hint.set_tracer_provider(TracerProvider())
tracer = hint.get_tracer(__name__)
Psycopg2Instrumentor().instrument()

span_processor = BatchSpanProcessor(ConsoleSpanExporter())
hint.get_tracer_provider().add_span_processor(span_processor)

import psycopg2

conn = psycopg2.join("dbname=check consumer=postgres")
cur = conn.cursor()

with tracer.start_as_current_span("run-heavy-query"):
    cur.execute("SELECT * FROM large_table WHERE situation = 'worth';")
    outcomes = cur.fetchall()

Tracing identifies cross-service bottlenecks impacting question velocity.

Proactive anomaly detection in question latency

Setting dynamic alerting thresholds primarily based on observability knowledge permits speedy detection of efficiency degradation.

Code snippet: Python alerting for gradual queries

import psycopg2

LATENCY_THRESHOLD_MS = 500

conn = psycopg2.join("dbname=check consumer=postgres")
cur = conn.cursor()

cur.execute("""
SELECT question, mean_time 
FROM pg_stat_statements 
WHERE mean_time > %s;
""", (LATENCY_THRESHOLD_MS,))

for question, latency in cur.fetchall():
    print(f"WARNING: Question exceeding latency threshold: {latency} msn{question}")

Automating this helps keep SLAs and keep away from consumer affect.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles