
Build observable application using AWS Distro for OpenTelemetry, AWS Native and AWS Managed Open Source Services
Build a complete observability solution using ADOT, AWS X-Ray, Amazon CloudWatch, Amazon Managed Service for Prometheus and Amazon Managed Grafana
Modern containerized applications require comprehensive observability to ensure reliability, performance, and quick issue resolution. When you are running any application on any platform, you need visibility into three key areas:
- Metrics: Application performance and resource utilization
- Traces: Request flow across distributed services
- Logs: Detailed application and system events
This ensures that you are well aware of what is going on in your application and how it is behaving with variations of incoming traffic. Traditional monitoring approaches often require complex setups with multiple tools that don't integrate well. However, AWS provides solution with its native as well as managed open source offerings that addresses all three pillars of observability seamlessly.
This blog demonstrates how to instrument your application using OpenTelemetry SDK and use AWS Distro for OpenTelemetry (ADOT) collector to ship telemetry data to your desired destination from your local environment. It also guides you to build a complete observability solution for an application hosted on Amazon ECS Fargate using the following services -
- ADOT - a secure, production-ready, AWS-supported distribution of the OpenTelemetry project.
- Amazon Managed Service for Prometheus (AMP) - a serverless, Prometheus-compatible monitoring service for container metrics that makes it easier to securely monitor container environments at scale.
- Amazon Managed Grafana (AMG) - a fully managed service based on open-source Grafana that makes it easier for you to visualize and analyze your operational data at scale.
- AWS X-Ray - a service that collects data about requests that your application serves, and provides tools that you can use to view, filter, and gain insights into that data to identify issues and opportunities for optimization.
- Amazon CloudWatch Logs - enables you to centralize the logs from all of your systems, applications, and AWS services that you use, in a single, highly scalable service.
Prerequisites
You should have the following setup pre-configured in your local environment:
- Docker and Docker Compose
- AWS CLI configured with credentials - One of local CLI access and another set for ADOT configuration for local environment.
Application Instrumentation
I have developed a Flask application that exposes the following endpoints:
- /health - Health check
- /api/data - Sample data endpoint
- /external - External service call
- /error - Error simulation
You may directly clone the project using the following commands
git clone https://github.com/Saborni/ecs-adot-prometheus-grafana.gitcd ecs-adot-prometheus-grafanaThe first step is to instrument your application using OTel SDK. The OTel SDK provides standardized instrumentation for applications to generate telemetry data (metrics, traces, and logs) without vendor lock-in. It acts as the bridge between your application code and observability backends.
First you will need to add the following import statements.
from opentelemetry import trace, metricsfrom opentelemetry import _logsfrom opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporterfrom opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporterfrom opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporterfrom opentelemetry.instrumentation.flask import FlaskInstrumentorfrom opentelemetry.instrumentation.requests import RequestsInstrumentorfrom opentelemetry.sdk._logs import LoggerProvider, LoggingHandlerfrom opentelemetry.sdk._logs.export import BatchLogRecordProcessorfrom opentelemetry.sdk.metrics import MeterProviderfrom opentelemetry.sdk.metrics.export import PeriodicExportingMetricReaderfrom opentelemetry.sdk.resources import Resourcefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorThen you will need to configure your application for generating logging, tracing and metrics and use corresponding OTLP exporters for each of those data type
# Configure logging and OTLP log exporterlogger_provider = LoggerProvider(resource=resource)_logs.set_logger_provider(logger_provider)logger_provider.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter()))handler = LoggingHandler(level=logging.NOTSET, logger_provider=logger_provider)handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))logger = logging.getLogger()logger.addHandler(handler)logger.setLevel(logging.INFO)
# Configure tracing and OTLP trace exportertrace.set_tracer_provider(TracerProvider(resource=resource))tracer = trace.get_tracer(__name__)span_processor = BatchSpanProcessor(OTLPSpanExporter())trace.get_tracer_provider().add_span_processor(span_processor)
# Configure metrics and OTLP metric exportermetric_reader = PeriodicExportingMetricReader(OTLPMetricExporter(),export_interval_millis=5000)metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[metric_reader]))meter = metrics.get_meter(__name__)You can define your own custom metrics as needed.
# Create custom metricsrequest_counter = meter.create_counter("zapp_http_requests_total", description="Total HTTP requests")exception_counter = meter.create_counter("zapp_http_exceptions_total", description="Total Exceptions requests")request_duration = meter.create_histogram("zapp_http_request_duration_seconds", description="HTTP request duration")Please note that instrumentation for logging behaviour will not be required if your logging destination is Amazon CloudWatch Logs as ECS Fargate provides native support to ship your application logs using 'awslogs' driver. For any other destination, use 'firelens' driver. Read through this document for your reference.
Local Testing
Once you have instrumented your application, it is necessary to test your application and observe how your application observability data is collected.

For local testing, I have used Docker compose to bring up the following components:
- Instrumented application container.
- ADOT container.
- Prometheus container with remote write config enabled.
The ADOT container uses otlp receiver to collect logs, metrics and traces and ship them to CloudWatch Logs, local Prometheus contianer and X-Ray.
receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 http: endpoint: 0.0.0.0:4318
processors: ...
exporters: awsxray: prometheusremotewrite: endpoint: ${env:AWS_PROMETHEUS_ENDPOINT} # auth: # authenticator: sigv4auth resource_to_telemetry_conversion: enabled: true awscloudwatchlogs: log_group_name: "/aws/ecs/zap-adot-logs" log_stream_name: "zap-adot-stream" region: ${env:AWS_REGION}...The Docker compose file used:
services: zap-app: build: ../zap-app ports: - "5000:5000" environment: - OTEL_EXPORTER_OTLP_ENDPOINT=http://adot-collector:4317 networks: - monitoring adot-collector: image: public.ecr.aws/aws-observability/aws-otel-collector:v0.44.0 command: ["--config=/etc/otelcol-contrib/config.yaml"] volumes: - ./adot-config.yaml:/etc/otelcol-contrib/config.yaml ports: - "4317:4317" # OTLP gRPC - "4318:4318" # OTLP HTTP environment: - AWS_REGION=us-east-1 - AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} - AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} - AWS_PROMETHEUS_ENDPOINT=http://prometheus:9090/api/v1/write networks: - monitoring...Please ensure that the IAM credentials passed to ADOT collector in your compose file has the following permission to push logs to CloudWatch and traces to X-Ray.
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:DescribeLogGroups", "logs:DescribeLogStreams", "logs:PutLogEvents", "logs:GetLogEvents", "logs:FilterLogEvents" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "xray:PutTraceSegments", "xray:PutTelemetryRecords", "xray:GetSamplingRules", "xray:GetSamplingTargets", "xray:GetSamplingStatisticSummaries" ], "Resource": "*" } ]}
Now deploy the complete setup locally using
cd localdocker-compose up --buildAccess your application using -
http://localhost:5000/health .Also, analyse if your custom metrics are getting pushed to your local Prometheus instance:
http://localhost:9090/ Also, validate if traces are getting pushed to AWS X-Ray and logs are pushed to the Log group as specified in ADOT config file.
AWS Architecture
For AWS deployment, I have used the ADOT Collector as a sidecar container alongside my application in ECS Fargate tasks. Please refer to this blog to know more on the types of deployment pattern.

This pattern provides:
- Centralized telemetry collection without modifying application code
- Secure, private communication via VPC endpoints
- Managed services that scale automatically
- Cost optimization through efficient data routing
Use the following command for deploying to AWS:
cd cloudformationsh deploy-0-1-2.shThe deployment is achieved using a three-tier CloudFormation approach:
1. Network Infrastructure (VPC + ALB)
Creates secure networking with VPC endpoints for:
- ECR (container registry access)
- AMP/AMG (observability services)
- X-Ray and CloudWatch (telemetry destinations)
2. Observability Services (AMP + AMG)
Provisions managed Prometheus and Grafana workspaces with:
- Automatic scaling and high availability
- Built-in security and compliance
- Integration with IAM Identity Center
3. Application Stack (ECS Fargate)
Deploys your application with ADOT sidecar pattern:
- Task definition with proper IAM roles
- Service discovery and load balancing
- Automated log collection via awslogs driver
The ADOT Collector configuration is crucial for proper telemetry routing. Here is the list of available config file that is prebaked in the ADOT collector container. I have reused the
ecs-amp-xray.yaml config file for my ADOT collector container.extensions: health_check: sigv4auth: region: ${env:AWS_REGION}
receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 http: endpoint: 0.0.0.0:4318 awsecscontainermetrics:
processors: batch/traces: timeout: 1s send_batch_size: 50 batch/metrics: timeout: 60s resourcedetection: detectors: - env - system - ecs - ec2 filter: metrics: include: match_type: strict metric_names: - ecs.task.memory.reserved - ecs.task.memory.utilized - ecs.task.cpu.reserved - ecs.task.cpu.utilized - ecs.task.network.rate.rx - ecs.task.network.rate.tx - ecs.task.storage.read_bytes - ecs.task.storage.write_bytes - container.duration
exporters: awsxray: prometheusremotewrite: endpoint: ${env:AWS_PROMETHEUS_ENDPOINT} auth: authenticator: sigv4auth resource_to_telemetry_conversion: enabled: true
service: pipelines: traces: receivers: [otlp] processors: [resourcedetection, batch/traces] exporters: [awsxray] metrics/application: receivers: [otlp] processors: [resourcedetection, batch/metrics] exporters: [prometheusremotewrite] metrics: receivers: [awsecscontainermetrics] processors: [filter] exporters: [prometheusremotewrite]
extensions: [health_check, sigv4auth]Kindly note that if you are placing your task in a public subnet, you can use the public container image of ADOT collector -
public.ecr.aws/aws-observability/aws-otel-collector:latest However, in this example, since my task is in a private subnet without any NAT Gateway routes, I have re-tagged the public image and pushed it to my private ECR repository and used it in the CloudFormation template.
Observability in Action
Once deployed, try accessing the application over the ALB endpoint appending the following endpoints:
http://LoadBalancerURL/health Replace `LoadBalancerURL` with the url of the ALB created in the infrastructure stack. Try accessing the other endpoints exposed by your Flask application.
You can observe your application through multiple lenses:
Traces in AWS X-Ray

Metrics in Amazon Managed Grafana

Logs in CloudWatch

Best Practices
Security
- Use VPC endpoints to avoid internet traffic
- Apply least-privilege IAM policies
- Enable encryption in transit and at rest
- Regularly rotate credentials
Performance
- Configure appropriate batch sizes in ADOT
- Use sampling for high-volume traces
- Set retention policies for cost optimization
- Monitor collector resource usage
Cost Optimization
- Use metric filtering to reduce ingestion costs
- Implement log retention policies
- Consider sampling strategies for traces
- Monitor AMP and AMG usage regularly
CleanUp
Once you have tested, proceed with the deletion of the stacks sequentially
aws cloudformation delete-stack --stack-name ecs-adot-amp-amg-ecs-appaws cloudformation delete-stack --stack-name ecs-adot-amp-amg-monitoring aws cloudformation delete-stack --stack-name ecs-adot-amp-amg-vpc-albConclusion
Building observability into ECS applications doesn't have to be complex. By leveraging ADOT, AMP, and AMG, you can create a production-ready monitoring solution that provides deep insights into your containerized applications while maintaining security and cost efficiency. The combination of local development capabilities and AWS-managed production services makes this approach both developer-friendly and operations-ready. Start with the local environment to validate your setup, then deploy to AWS for a fully managed, scalable observability platform.
Ready to implement this solution? Check out the complete code and CloudFormation templates in the GitHub repository
References
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article