AWS-Native LLM Observability with OpenTelemetry

By Serhat Düzen on Dec 1, 2026, 6:55:53 PM

aws-native-llm-observability-token-cost-latency

Teams that put a large language model behind an application quickly run into three questions. Which application is spending the tokens? What does one user request cost end to end? Where did the time go: the browser, the service, the database or the model?

Cost dashboard: total, per-model cost, cost per request and pie charts by model and by service

This post builds an answer using only AWS services and OpenTelemetry. A small demo application, a fictional air-conditioner repair service called CoolFix, calls Amazon Bedrock through a LiteLLM proxy. Traces go to AWS X-Ray, metrics go to Amazon Managed Service for Prometheus (AMP), and Amazon Managed Grafana (AMG) draws both.

Everything is Terraform: the servers, the roles, the account-level tracing switch, the secrets, the rollout of the application stack, and the Grafana data sources and dashboards. There is no setup script to run in a particular order on a particular laptop. You change a file, run terraform plan, read the difference, and apply it. Every file mentioned below is in the repository: github.com/kloia/observability-aws-litellm-demo. File paths are relative to the repository root.

No access keys appear anywhere. The Collector, Grafana and the server use IAM roles, and generated secrets live in Parameter Store.

 

Architecture

One chat message is one trace. It starts with a click in the browser, passes through the web service, the chatbot, Postgres, LiteLLM and Bedrock, and includes the asynchronous triage worker that picks the ticket up later.

Architecture: apps call LiteLLM and Bedrock; the Collector sends traces to X-Ray and metrics to AMP; Grafana reads both


Component

Role

CoolFix apps

Web front end, chatbot, triage worker, technician assistant (apps/)

LiteLLM

One gateway in front of Bedrock; apps use the model names haiku, sonnet and sonnet-4-5 (litellm/config.yaml)

OpenTelemetry Collector

Receives OTLP, derives metrics from traces, signs requests with SigV4 (otel/otel-collector-aws.yaml)

AWS X-Ray

Trace storage, written to CloudWatch Logs by Transaction Search

AMP

Metric storage

AMG

Dashboards, sign-in through IAM Identity Center


 

The Lab

The infrastructure is two Terraform root modules, applied in order. The split is not taste. The Grafana provider needs the workspace address and a token, and those exist only after the first apply.

Two Terraform stacks: platform first, then Grafana content, connected through outputs


Stack

Creates

Needs

terraform/

Server, IAM, AMP, AMG, Transaction Search, secrets, S3 package, rollout

An AWS session, Identity Center user id

terraform/grafana/

Data sources, folder, dashboards

The first stack's outputs


 

Step 1 - The platform

bash
cd terraform

cp terraform.tfvars.example terraform.tfvars # owner, cost_center, vpc_id, subnet_id, grafana_admin_user_id

terraform init

terraform plan

terraform apply

 

What the platform stack creates:

  • The server. An EC2 instance in a private subnet that runs the application stack with Docker Compose. There is no inbound access and no SSH; you reach it with AWS Systems Manager Session Manager. The instance role holds the Bedrock invoke permission and write access to AMP (terraform/main.tf).
  • Metrics and dashboards. An AMP workspace, an AMG workspace whose IAM role can read only that AMP workspace plus the AWS-managed CloudWatch access policy, and a role association that makes one Identity Center user an administrator. Without the association the user signs in and sees "no access" (terraform/grafana.tf).
  • A Grafana service account and token. The second stack uses them. The token is a sensitive output, valid for 30 days, and replaced by Terraform when it expires.
  • A scoped X-Ray group. It limits X-Ray views to the demo services, which matters when the account also holds unrelated traces.

Every taggable resource carries the Project, Environment, Owner and CostCenter tags, set once through the provider's default tags.

 

Step 2 - Transaction Search, also in Terraform

X-Ray accepts OpenTelemetry data on its own OTLP endpoint, but only when CloudWatch Transaction Search is enabled. Without it, the endpoint rejects the traces. The AWS provider has no resource for this setting. AWS documents a CloudFormation template for it, so we apply that template through Terraform and keep it in the same plan and state:

Two facts matter before you apply it. The setting is account-wide, so agree it with whoever owns the account. And AWS states that Transaction Search must be off before CloudFormation can enable it, so an account that already turned it on by hand has to turn it off first.

 

Step 3 - Secrets and the rollout of the stack

terraform/secrets.tf generates the LiteLLM key and the database passwords with random_password and stores them as encrypted Parameter Store values. They are never outputs and never in git.

terraform/deploy.tf rolls the application stack out:

1. An archive_file zips the Compose file, the Collector and LiteLLM configuration and the application sources.

2. The zip goes to a private S3 bucket under a key that contains its hash.

3. An SSM association runs on the server whenever that key changes. It downloads the package, writes the environment file from Parameter Store and runs docker compose up -d --build.

Edit a Collector rule, run terraform apply, and the new configuration reaches the server and restarts the right container. The association body is a short template, terraform/templates/apply.sh.tftpl. It is a shell command, as any server bootstrap is, but Terraform owns when it runs, with which package and with which secrets, and shows that in the plan.

 

Step 4 - The Collector

All telemetry passes through one OpenTelemetry Collector, configured in otel/otel-collector-aws.yaml.

Collector pipelines: traces to X-Ray and two connectors; connectors and LiteLLM metrics to AMP


Authentication without keys.
The sigv4auth extension signs outgoing requests with the instance role. One signer targets the xray service for traces and another targets aps for remote write. The configuration contains no credentials.

Traces go to X-Ray, and also become metrics. The traces pipeline exports to the X-Ray OTLP endpoint and to two connectors. The spanmetrics connector turns spans into request, error and duration metrics per service and span name. Its dimensions are few on purpose: span names are routes, SQL verbs and button names, never ids or text, so the number of time series stays bounded.

Per-application token counts. Every LLM request span carries its token counts, the model and the calling application. A sum connector adds them up per application and model, and a deltatocumulative processor converts the result, because the connector emits deltas and Prometheus remote write needs cumulative values. These counters are the single source for every token and cost panel, so the numbers on the dashboards always agree with each other.

yaml
sum/tokens:

spans:

llm.app.tokens.input:

source_attribute: gen_ai.usage.input_tokens

conditions:

- 'attributes["gen_ai.usage.input_tokens"] != nil and attributes["metadata.user_api_key_end_user_id"] != nil'

attributes:

- key: gen_ai.request.model

- key: metadata.user_api_key_end_user_id

 

One source for every number. LiteLLM can also export its own token and duration metrics. This build does not use them: the request span already carries the application, the model and the token counts, and reading everything from one place keeps the model view and the application view consistent. The same spans feed the traces, so a number on a dashboard can always be checked against a trace.

LiteLLM itself is configured in litellm/config.yaml. Three model names (haiku, sonnet, sonnet-4-5) hide the Bedrock inference profile ids, so applications never change when a model version does. Each application picks its own: the chatbot uses haiku, the technician assistant uses sonnet, and the triage worker uses sonnet-4-5. That is what makes the per-model and per-application charts below worth looking at. LiteLLM needs no custom code for this. Its OpenTelemetry callback emits the spans and metrics, and each application passes its own name in the standard user field of the OpenAI-compatible request, which LiteLLM exports on the span as metadata.user_api_key_end_user_id. One setting deserves a decision before you publish anything: with turn_off_message_logging: false, prompts and responses are exported on spans. In production, set it to true.

 

Step 5 - Grafana as code

The second stack, terraform/grafana/, uses the Grafana provider with the token from the first stack.

bash
cd terraform/grafana

terraform init

terraform plan

terraform apply

 

terraform/grafana/main.tf declares:

  • An AMP data source signed with the workspace role through the AWS credential chain. It sets timeInterval: 60s to match the export interval (see "What broke").
  • A CloudWatch data source for the trace tables. The workspace does not ship an X-Ray plugin, and installing plugins has no Terraform resource, so traces are read from the aws/spans log group with Logs Insights instead of from X-Ray directly.
  • A folder and one dashboard per file in dashboards/, through fileset. Add dashboards/grafana-mine.json, run terraform apply, and it appears.

Because dashboards are resources, a change made by hand in the Grafana UI shows up as a difference in the next plan.

 

Step 6 - Run the app and make some traffic

Open the site through Session Manager port forwarding and browse to localhost:18080:

bash
aws ssm start-session --target "$(terraform -chdir=terraform output -raw instance_id)" \

--document-name AWS-StartPortForwardingSession \

--parameters '{"portNumber":["8080"],"localPortNumber":["18080"]}'

 

Session Manager closes an idle forward after a while. A request to the home page every 45 seconds keeps it open while you work.


The CoolFix chat in the browser


Open the chat, click a quick reply and describe a fault until the assistant opens a ticket. All traffic in the demo comes from real browser use, so the numbers in the dashboards correspond to actual clicks and chats. The triage worker picks the ticket up a few seconds later and assigns a technician. Before you move on, check Transaction Search read-only:

bash
aws xray get-trace-segment-destination


Expect
"Destination": "CloudWatchLogs" and "Status": "ACTIVE".

 

Step 7 - The dashboards

Five dashboards come from dashboards/:

Dashboard

What it answers

CoolFix

Request rate, errors and latency per service and span

LLM

Tokens, operation count and p95 duration per model

Traces

Span counts and durations per service, latest spans and slowest LLM calls

RUM

Browser-side spans: page loads and button clicks

LLM cost

Estimated Bedrock spend


The LLM dashboard answers the model questions: tokens, request count and latency per model, taken from the span counters and span metrics the Collector derives.

LLM dashboard: tokens by model and by type, p95 and mean latency per model

The CoolFix dashboard shows the applications. It combines span-derived metrics with the ticket flow, so one screen answers which service is slow and which model it called.

CoolFix dashboard: chat requests, tickets created and triaged, requests and p95 latency per service

LLM calls and latency are split by application and model, which is the label the Collector adds from the span attributes.

LLM calls and p95 latency by application and model

Tool calls and database queries come from spans too, with bounded names such as the tool name or the SQL verb. The ticket funnel at the bottom counts chats, tickets created and tickets triaged.

Tool calls, database queries, database p95 latency and the ticket funnel

The RUM dashboard shows what the visitor's browser did: page loads, button clicks and how long the chat took in the browser compared with the server.

RUM dashboard: page loads, clicks by button, page load time and the browser versus server view of a chat

The trace tables are Logs Insights queries on the aws/spans log group, so they work without an extra plugin. The trade-off is that there is no drawn service map. Open a trace id in the X-Ray or CloudWatch console to see one chat message end to end.

Following one chat message. A trace is the path of one request, drawn as nested spans. The screenshot below is a real chat from the demo, opened in Grafana's Explore: the click in the browser, coolfix-web, coolfix-chatbot, the LiteLLM proxy and Amazon Bedrock, with the Postgres calls beside them.

One trace: browser click, coolfix-web, coolfix-chatbot, LiteLLM and Amazon Bedrock with the time spent in each

Read it from the top. The browser waited 1.33 s for the answer. coolfix-web accounts for 1.22 s of that, all of it spent waiting for coolfix-chatbot (1.21 s). The chatbot made two Postgres calls of 2.7 ms and 1.9 ms and one call to LiteLLM, which took 1.17 s. Inside LiteLLM the router called Bedrock for 1.16 s. Upstream is the caller and downstream is the callee: every bar sits inside the bar of the service that called it, and the part of a bar not covered by its children is time that service spent on its own. Here 1.16 s of the 1.33 s is the model. Everything else in the path adds about 170 ms, so tuning the application would not make this chat faster; a smaller model or a shorter answer would.

Grafana draws this waterfall with the X-Ray data source plugin, which Amazon Managed Grafana does not ship and which has no Terraform resource. Installing it is a workspace setting plus one plugin call, so it is the one step in this build that stays outside the code. The Terraform-only route is the Logs Insights tables above, with the trace id opened in the X-Ray or CloudWatch console.

 

Step 8 - Putting a price on tokens

Token counts alone do not tell a finance team much. The cost dashboard (dashboards/grafana-cost.json) multiplies token counts by the Bedrock on-demand price for the EU cross-region inference profile, taken from the AWS Price List API (service AmazonBedrockFoundationModels, region eu-west-1):


Model

Input, USD per 1M tokens

Output, USD per 1M tokens

Claude Haiku 4.5

1.10

5.50

Claude Sonnet 4.6

3.30

16.50

Claude Sonnet 4.5

3.30

16.50


The prices are written into the PromQL: increase(...) over the selected range times the input price plus the same for output, divided by one million. One term, for Haiku input and output:

promql

(sum(increase(llm_app_tokens_input_total{gen_ai_request_model=~".*haiku.*"}[$__range])) or vector(0)) * 1.1

+ (sum(increase(llm_app_tokens_output_total{gen_ai_request_model=~".*haiku.*"}[$__range])) or vector(0)) * 5.5

 

The or vector(0) keeps a model with no traffic at zero instead of "No data". The dashboard has a total, a cost per model, a cost per request, one pie chart by model, one by service, and two time series. Prompt caching and batch inference are priced differently and are not included, so treat the number as an estimate.

Cost dashboard: total, per-model cost, cost per request and pie charts by model and by service

 

Clean up

bash

terraform -chdir=terraform/grafana destroy

terraform -chdir=terraform destroy

 

Destroy the Grafana stack first, because it needs the workspace to exist. The platform destroy removes the server, AMP, AMG, the roles, the package bucket and the Transaction Search stack, which turns that account setting off again. The dashboards stay in git. While the stack runs you pay for the instance, the disk and the two managed workspaces, plus Bedrock usage. Stopping the instance ends compute charges but not the workspaces or the disk.

 

What broke when we ran it for real

X-Ray rejected the traces. The OTLP endpoint refuses data until CloudWatch Transaction Search is enabled. Nothing in the Collector logs says why in plain words, so it became its own stack, with the account-wide caveat written next to it.

The rate panels were empty. Grafana's default minimum interval is 15 seconds, and we export every 60. A rate() window then holds one sample and draws nothing. Setting timeInterval: 60s on the data source fixed every panel at once.

Two sources, two totals. The by-model pie and the by-service pie disagreed by a factor of three, because they read two different sets of counters. The span counters matched the per-call cost LiteLLM records on its own spans, so we moved every panel to them and removed the second source.

The cost total went blank. With no Sonnet traffic, the Sonnet term returned nothing and the sum of both models showed "No data" while the Haiku box showed a value. Wrapping each term in or vector(0) fixed it.

The by-service pie started empty. increase() needs two samples in the window, so a single test chat drew nothing. A second chat filled the pie.

The X-Ray plugin could not be declared. Amazon Managed Grafana does not ship it, and Terraform has no resource that installs a Grafana plugin. Rather than keep a manual step, the trace tables read the aws/spans log group through the CloudWatch data source, which is built in.

The Grafana provider cannot configure itself from the same apply. It needs a token that does not exist yet on the first run, so the Grafana content lives in a second stack that reads the first stack's outputs.

The port forward died. Session Manager closes an idle session, so the site stopped responding while we were taking screenshots. The keepalive request fixed it.

Front-end packages did not match. The browser OpenTelemetry packages tagged as latest are incompatible with each other, so the versions are pinned in the web image.

The lesson from the first three: the failures were quiet. Nothing crashed. Panels were empty, or a switch was missing, or a number was wrong. Check the data path from one end to the other after every change, not just the deployment.

 

Limitations worth knowing

  • Prices are a snapshot. The numbers come from the AWS Price List API at the time of writing, are hard-coded in the dashboard, and exclude prompt caching and batch inference.
  • Prompts can leave the application. With turn_off_message_logging: false, prompt and response text is exported on spans. Set it to true for production.
  • Transaction Search is account-wide. Agree the change with whoever owns the account, and turn it off before the first apply.
  • The trace waterfall needs a plugin. The Terraform-managed trace tables work without one. Grafana's waterfall and service map come from the X-Ray data source plugin, which cannot be installed from Terraform.
  • The rollout is an SSM association. It restarts the Compose stack on change. It is configuration management, not a deployment strategy with rollbacks.
  • This is a demo topology. One instance runs the stack, with no high availability. Reuse the Collector configuration, not the topology, in production.

 

Conclusion

LLM observability does not need a separate product. A gateway that emits OpenTelemetry, one Collector that signs its own requests, and three managed AWS services were enough to answer the three opening questions: which application spends the tokens, what a request costs, and where the time goes. Because the platform, the account switch, the secrets, the rollout, the data sources and the dashboards are all Terraform, the whole thing can be reviewed in a plan, rebuilt and destroyed on demand.

 

References

 

FAQ

Do I need to change my applications?

Only to send OpenTelemetry and to pass their own name in the user field of the LLM request. LiteLLM exports that name on the span, and the Collector uses it as the application label.

Why derive the counters from spans?

The span already names the application, the model and the token counts, so one source answers every question, and each number can be traced back to a request.

Why does AMP store token counts as cumulative sums?
Prometheus remote write needs cumulative values. The sum connector emits deltas, so a deltatocumulative processor converts them.
Can I use another Grafana?

Yes. The data sources use SigV4, so any Grafana that can assume an IAM role works. This build uses Amazon Managed Grafana because it needs no servers.

Back to top

Get Email Notifications

No Comments Yet

Let us know what you think