Mobile Betting · 17 / 26

Telemetry and KQL (Kusto Query Language) Examples

OpenTelemetry traces, metrics and events for the mobile betting platform, with Kusto queries for latency, KYC automation, protection audits, time to intervention and bias.

What the telemetry is for

OpenTelemetry is the vendor-neutral standard for traces, metrics and logs. The platform emits one trace per work item, such as a KYC case, a support case or an intervention, and links the steps of a case by a case identifier, so an operator can answer three questions: is it fast and available, is it correct and safe, and what does it cost. Telemetry carries identifiers, outcomes and measurements. It never carries documents, identity, location or gambling history (ADR-006).

Traces

Spans for each step of an item, parent and child, from intake to the account platform. One trace identifier follows the item across services and the gateway.

Metrics

Counters and histograms for item latency, decisions, protections, tokens, cost and guardrail blocks. Cheap to store and good for alerts.

Events

Business events with a name and properties: KYC decided, harm marker, protection applied, intervention sent, restriction placed or released, message sent, guardrail block.

Correlation

The W3C trace context header travels from intake through the AI (artificial intelligence) gateway and tool gateway, so their logs join the same trace.

The shape of a trace

A trace for one KYC case A root span for the KYC case contains child spans for the input scan, a fast-model extraction, the identity checks, a policy check, the apply tool call and the output scan, drawn as bars on a shared time axis. ONE KYC CASE · ILLUSTRATIVE 4.6 SECONDS kyc.item 4600 ms airs.scan.input 140 ms gateway.llm_call mb-fast 1500 ms kyc.checks age, sanctions 1450 ms retrieval.search 220 ms policy.check 60 ms airs.scan.tool_args 120 ms tool.call apply_decision 920 ms airs.scan.output 100 ms service span gateway or tool retrieval security scan
Each component shows up as a span, so the slow or failing step is visible at a glance.
SpanKindKey attributes
kyc.itemServer (root)case.id (hashed), stage, jurisdiction, outcome
airs.scan.input, airs.scan.output, airs.scan.tool_argsClientairs.profile, airs.action, airs.detections (names only)
gateway.llm_callClientgen_ai.request.model (alias), gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gateway.cost_usd, gateway.fallback_used
retrieval.searchClientknowledge.index, filter.jurisdiction, results.count, top.score
kyc.checksClientcheck.age, check.location, check.sanctions (results only, no identity)
policy.checkInternalpolicy.rule, policy.decision
tool.callClienttool.name, tool.outcome, tool.basis

What must never be in telemetry

DataRuleHow
Document images and message textNeverNot an attribute. Debugging uses the masked cases table in the lakehouse
Identity, contacts, location, device and gambling historyNever in clearDropped or hashed by the collector before export
Case and player identifiersHashedKeyed hash, so queries can group by case without exposing it
Blocked contentNeverRecord the detection names and the verdict only
Bands, scores and basesAllowedNeeded for protection and fairness analysis

Instrumenting the service

A sketch in Python with the OpenTelemetry SDK (Software Development Kit) and the Azure Monitor distribution, which sends to Application Insights. The root span is a server span so it appears as a request; child spans appear as dependencies; business events are logged with a custom event name. Check the current package and attribute names before you build.

telemetry.py · spans, metrics and business events
import logging, os
from opentelemetry import trace, metrics
from opentelemetry.trace import SpanKind
from azure.monitor.opentelemetry import configure_azure_monitor

configure_azure_monitor(connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"])
tracer = trace.get_tracer("betting.platform")
meter = metrics.get_meter("betting.platform")
item_ms = meter.create_histogram("mb.item.duration", unit="ms")
blocks = meter.create_counter("mb.guardrail.blocks")
log = logging.getLogger("mb.events")

def process_kyc(application, jurisdiction):
    with tracer.start_as_current_span("kyc.item", kind=SpanKind.SERVER) as item:
        item.set_attributes({"case.id": hash_id(application["case_id"]), "stage": "kyc", "jurisdiction": jurisdiction})

        with tracer.start_as_current_span("airs.scan.input") as sp:
            verdict = scan(prompt=application["document_text"], case=application["case_id"], model="mb-fast")
            sp.set_attributes({"airs.profile": "betting-documents-prod", "airs.action": verdict["action"]})
            if verdict["action"] != "allow":
                blocks.add(1, {"detection": detection_name(verdict), "stage": "input"})
                log.warning("guardrail block", extra={"microsoft.custom_event.name": "guardrail.block",
                            "case.id": hash_id(application["case_id"]), "airs.detection": detection_name(verdict)})
                return route_to_analyst(application, reason="blocked")

        with tracer.start_as_current_span("gateway.llm_call") as llm:
            fields, usage = read_id_document_fields(application)
            llm.set_attributes({"gen_ai.request.model": "mb-fast", "gen_ai.usage.input_tokens": usage.input,
                                "gen_ai.usage.output_tokens": usage.output, "gateway.cost_usd": usage.cost})
        ...
        log.info("kyc decided", extra={"microsoft.custom_event.name": "kyc.decided", "case.id": hash_id(application["case_id"]),
                 "basis": decision.basis, "outcome": decision.outcome})
        item_ms.record(elapsed_ms(item), {"stage": "kyc"})

A collector in the middle

An OpenTelemetry Collector receives telemetry from the service and the gateway, removes or hashes sensitive attributes, keeps every error and every block, samples the rest, and sends it to Azure Monitor for operations and to the lakehouse for long-term analysis.

otel-collector.yaml · redact, keep what matters, fan out
receivers:
  otlp:
    protocols: { grpc: {}, http: {} }

processors:
  attributes/privacy:
    actions:
      - { key: document.text,  action: delete }
      - { key: player.email,   action: delete }
      - { key: player.id,      action: hash }
      - { key: device.ip,      action: hash }
  tail_sampling:
    decision_wait: 10s
    policies:
      - { name: keep-errors, type: status_code, status_code: { status_codes: [ERROR] } }
      - { name: keep-blocks, type: string_attribute, string_attribute: { key: airs.action, values: [block] } }
      - { name: sample-rest, type: probabilistic, probabilistic: { sampling_percentage: 10 } }
  batch: {}

exporters:
  azuremonitor:
    connection_string: ${env:APPLICATIONINSIGHTS_CONNECTION_STRING}
  otlphttp/lakehouse:
    endpoint: ${env:LAKEHOUSE_OTLP_ENDPOINT}

service:
  pipelines:
    traces:  { receivers: [otlp], processors: [attributes/privacy, tail_sampling, batch], exporters: [azuremonitor, otlphttp/lakehouse] }
    metrics: { receivers: [otlp], processors: [batch], exporters: [azuremonitor] }
    logs:    { receivers: [otlp], processors: [attributes/privacy, batch], exporters: [azuremonitor, otlphttp/lakehouse] }

KQL queries operators use

These queries use the workspace-based Application Insights tables in Log Analytics: AppRequests for the root span, AppDependencies for child spans, AppEvents for business events and AppMetrics for metrics. Custom attributes appear in the Properties column. Table and column names can differ with your setup, so adjust them to your workspace. The same Kusto Query Language also runs in Azure Data Explorer if you export telemetry there.

Item latency by stage

Median and 95th percentile processing time per stage, hourly, for the last day.

KQL
AppRequests
| where TimeGenerated > ago(1d) and Name in ("kyc.item", "support.case")
| extend stage = tostring(Properties["stage"])
| summarize items = count(), p50 = percentile(DurationMs, 50), p95 = percentile(DurationMs, 95)
    by stage, bin(TimeGenerated, 1h)
| order by TimeGenerated desc, stage asc

Where the time goes

Average and slowest duration for each step of an item, to find the step to optimise.

KQL
AppDependencies
| where TimeGenerated > ago(1d)
| where Name in ("airs.scan.input", "gateway.llm_call", "retrieval.search", "kyc.checks", "policy.check", "tool.call", "airs.scan.output")
| summarize calls = count(), avg_ms = avg(DurationMs), p95_ms = percentile(DurationMs, 95),
            failures = countif(Success == false)
    by Name
| order by p95_ms desc

KYC cases decided without a person

Share of KYC decisions by basis, by day. The headline measure of automation.

KQL
AppEvents
| where TimeGenerated > ago(14d) and Name == "kyc.decided"
| extend basis = tostring(Properties["basis"])
| summarize decisions = count() by basis, day = bin(TimeGenerated, 1d)
| evaluate pivot(basis, sum(decisions))
| extend total = rule_clear + analyst_approved
| extend auto_pct = round(100.0 * rule_clear / total, 1)
| order by day desc

Actions without a valid basis (must be zero)

Finds any protective or restrictive action with a missing or disallowed basis. Any row is an incident.

KQL
AppEvents
| where Name in ("protection.applied", "restriction.placed")
| extend basis = tostring(Properties["basis"])
| where isempty(basis) or basis !in ("rule_threshold", "specialist_approved", "player_request", "analyst_approved")
| project TimeGenerated, event = Name, case = tostring(Properties["case.id"]), basis, OperationId

Sends to excluded or at-risk players (must be zero)

Finds any marketing message sent to a player in an exclusion state. Any row is an incident.

KQL
AppEvents
| where Name == "message.sent" and tostring(Properties["purpose"]) == "marketing"
| extend state = tostring(Properties["exclusion_state"])
| where state != "clear"
| project TimeGenerated, channel = tostring(Properties["channel"]), state, OperationId

Guardrail blocks by detection

How often each Prisma AIRS detection fired, by hour, to spot an attack or a noisy rule.

KQL
AppEvents
| where TimeGenerated > ago(7d) and Name == "guardrail.block"
| extend detection = tostring(Properties["airs.detection"])
| summarize blocks = count(), cases = dcount(tostring(Properties["case.id"]))
    by detection, bin(TimeGenerated, 1h)
| order by TimeGenerated desc, blocks desc

Tokens and cost by model alias

Spend and token use per alias and per day, from gateway metadata.

KQL
AppDependencies
| where TimeGenerated > ago(14d) and Name == "gateway.llm_call"
| extend model = tostring(Properties["gen_ai.request.model"]),
         tin = toint(Properties["gen_ai.usage.input_tokens"]),
         tout = toint(Properties["gen_ai.usage.output_tokens"]),
         cost = todouble(Properties["gateway.cost_usd"])
| summarize calls = count(), input_tokens = sum(tin), output_tokens = sum(tout), cost_usd = round(sum(cost), 2)
    by model, day = bin(TimeGenerated, 1d)
| order by day desc, cost_usd desc

Time from harm marker to first intervention

How quickly the first protective action follows a medium or high marker, by band.

KQL
let markers = AppEvents | where Name == "harm.marker" | extend player = tostring(Properties["case.id"]), band = tostring(Properties["band"])
    | project marker_time = TimeGenerated, player, band;
let actions = AppEvents | where Name in ("protection.applied", "intervention.sent")
    | extend player = tostring(Properties["case.id"]) | project action_time = TimeGenerated, player;
markers
| join kind=inner (actions) on player
| where action_time >= marker_time
| summarize first_action = min(action_time) by player, marker_time, band
| extend minutes = datetime_diff("minute", first_action, marker_time)
| summarize p50 = percentile(minutes, 50), p95 = percentile(minutes, 95), cases = count() by band

Specialist and analyst queue age

How many cases are waiting for a person and for how long, to catch a stuck queue.

KQL
AppEvents
| where Name in ("case.routed", "case.closed")
| extend case = tostring(Properties["case.id"]), queue = tostring(Properties["queue"])
| summarize routed = minif(TimeGenerated, Name == "case.routed"), closed = maxif(TimeGenerated, Name == "case.closed") by case, queue
| where isnotnull(routed) and isnull(closed)
| extend age_hours = datetime_diff("hour", now(), routed)
| summarize waiting = count() by queue, age_bucket = case(age_hours < 4, "under 4 hours", age_hours < 24, "4 to 24 hours", "over 24 hours")

Wrongful restrictions

Restrictions placed and released as wrongful, by day, to tune thresholds.

KQL
AppEvents
| where TimeGenerated > ago(14d) and Name in ("restriction.placed", "restriction.released_wrongful")
| summarize events = count() by Name, day = bin(TimeGenerated, 1d)
| evaluate pivot(Name, sum(events))
| extend wrongful_pct = round(100.0 * restriction_released_wrongful / restriction_placed, 2)
| order by day desc

Intervention rates by segment (bias view)

Interventions and restrictions by permitted segment, as the input to the monthly bias review.

KQL
AppEvents
| where TimeGenerated > ago(90d) and Name in ("harm.marker", "intervention.sent", "restriction.placed")
| extend segment = tostring(Properties["segment"])
| summarize markers = countif(Name == "harm.marker"), interventions = countif(Name == "intervention.sent"), restrictions = countif(Name == "restriction.placed") by segment
| extend intervention_rate = round(100.0 * interventions / markers, 2), restriction_rate = round(100.0 * restrictions / markers, 2)
| order by markers desc

Alert: block rate spike

Compares the hourly block rate with its normal pattern and returns hours that are anomalously high. Use it as an alert query.

KQL
let items = AppRequests | where Name in ("kyc.item", "support.case")
    | make-series items = count() default = 0 on TimeGenerated from ago(14d) to now() step 1h;
let blocked = AppEvents | where Name == "guardrail.block"
    | make-series blocked = count() default = 0 on TimeGenerated from ago(14d) to now() step 1h;
items
| join kind=inner (blocked) on $left.TimeGenerated == $right.TimeGenerated
| project TimeGenerated, rate = series_divide(blocked, items)
| extend (flag, score, baseline) = series_decompose_anomalies(rate, 2.5)
| mv-expand TimeGenerated to typeof(datetime), rate to typeof(double), flag to typeof(int), score to typeof(double)
| where flag == 1 and TimeGenerated > ago(3h)

Service-level objectives and alerts

ObjectiveSignalTargetAlert
Fast KYCkyc.item p95Under 60 secondsp95 over target for 15 minutes
AvailableShare of items not ending in errorAt least 99.5%Below target for 10 minutes
Safe actionsActions without a valid basisZeroAny occurrence, page the on-call
Duty of care respectedSends to excluded or at-risk playersZeroAny occurrence, page the on-call
Scans on all trafficModel calls with a scan span100%Any unscanned model call
Attacks visibleBlock rate versus baselineWithin normal rangeAnomaly flagged for 1 hour
Prompt protectionTime from high marker to first actionp95 under 10 minutesOver target for an hour
No stuck casesCases waiting over 24 hoursUnder 1%Over target for a day
Few wrongful restrictionsRestrictions released as wrongfulUnder 0.5%Over target for a week
Cost under controlCost per KYC document, dailyWithin budgetOver 120% of the 7-day average

Dashboards

Operations

Item latency and errors by stage, step breakdown, tool health and gateway fallbacks.

Security and fraud

Blocks by detection, anomalies, step-up and restriction outcomes, scan coverage and actions without a basis.

Player protection

Markers by band, time to first action, interventions, specialist queue age and sends to excluded players.

Cost

Tokens and cost by model and stage, cost per document and case, and budget burn.

Build this for your business

This example is a player protection and operations platform for a licensed betting operator, but the same pattern, deterministic rules for every hard duty, a governed gateway, runtime security, protect-first automation and measured quality, fits any regulated, customer-facing service. We can scope a pilot on your own systems.

Book a discovery call