Tutorial · Scalable sites on AWS · AWS SQS
Observability and cost on AWS – CloudWatch, OpenTelemetry and X-Ray, alarms, dashboards, budgets, anomaly detection and tags
The pierogi shop's portal runs across several zones and scales itself – yet one Friday at 7 p.m. it returned errors for fifteen minutes without anyone noticing, and the monthly bill doubled. We build observability and cost control – metrics, logs and traces with OpenTelemetry, symptom-based alarms with a composite alarm, a dashboard in CDK, forecast-based budgets, cost anomaly detection, a tagging strategy and Savings Plans basics.
After moving to the architecture from the scalable portal tutorial, the pierogi shop's portal survived another TV appearance. Two weeks later, one Friday at 7 p.m., every tenth order failed for fifteen minutes – Halina found out from customers on Monday. The same month the AWS bill doubled because a worker was pulling images through NAT. Both problems have the same cure: seeing what is happening before customers or the accountant do.
Prerequisites: the stack from the scalable portal tutorial or any app on ECS/Lambda, AWS CLI v2, Node.js 22+, AWS CDK v2. Access to the Billing console (cost allocation tags are activated in the management account).
- 3 + 1
- signals – metrics, logs, traces – and cost
- 25.02.2027
- end of support for the X-Ray SDKs and daemon – maintenance mode since 25.02.2026
- up to 66%
- Compute Savings Plans discount – EC2, Fargate, Lambda
- up to 35%
- Database Savings Plans discount – since December 2025
What to measure: signals and SLOs
| Signal | Example in the pierogi shop | Where |
|---|---|---|
| Metrics (numbers over time) | requests/min, 5xx, p99, task count, database connections, orders/min | CloudWatch Metrics |
| Logs (events) | "order failed" with orderId, trace_id and the cause | CloudWatch Logs, Logs Insights |
| Traces (a request's path) | POST /orders → Aurora → SQS → worker, with the time of every step | X-Ray, Application Signals |
| Cost | USD per day per service and per project tag | Cost Explorer, Budgets, Anomaly Detection |
Web services fit the RED method (rate, errors, duration) – request count, error rate, latency – and resources fit USE (utilization, saturation, errors). From there you define an SLO, e.g. "99.9% of API requests over 30 days finish without a 5xx and faster than 1.5 s". The 0.1% is the error budget: about 43 minutes of "bad" operation per month. An alarm should fire when that budget burns faster than it should – not at every single hiccup.
Step 1. Instrumentation: OpenTelemetry, logs and EMF
npm install @opentelemetry/sdk-node @opentelemetry/api @opentelemetry/auto-instrumentations-node \
@opentelemetry/exporter-trace-otlp-proto @opentelemetry/exporter-metrics-otlp-proto \
@opentelemetry/sdk-metrics @opentelemetry/resource-detector-aws pino
OpenTelemetry, custom spans and metrics, logs with trace_id and EMF
// Loaded before the app: node --import ./dist/telemetry.js dist/server.js
import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto';
import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';
import { awsEcsDetector } from '@opentelemetry/resource-detector-aws';
// Exporters send OTLP to the collector sidecar (ADOT / CloudWatch agent) on localhost:4318,
// which forwards traces to X-Ray and metrics to CloudWatch. Endpoint: OTEL_EXPORTER_OTLP_ENDPOINT.
const sdk = new NodeSDK({
serviceName: 'pierogi-api',
traceExporter: new OTLPTraceExporter(),
metricReaders: [new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter(), exportIntervalMillis: 60_000 })],
instrumentations: [
getNodeAutoInstrumentations({
'@opentelemetry/instrumentation-fs': { enabled: false }, // noisy, rarely useful
}),
],
resourceDetectors: [awsEcsDetector], // cluster, task ARN, AZ as resource attributes
});
sdk.start();
process.on('SIGTERM', () => {
sdk.shutdown().catch(() => undefined); // flush spans before the task stops
});import { metrics, trace, SpanStatusCode } from '@opentelemetry/api';
import { pino } from 'pino';
const tracer = trace.getTracer('pierogi-api');
const meter = metrics.getMeter('pierogi-api');
const ordersPlaced = meter.createCounter('orders.placed', { description: 'Accepted orders' });
const orderValue = meter.createHistogram('orders.value', { unit: 'PLN', description: 'Order total' });
// Every log line carries trace_id – one click from a log to the whole trace.
export const log = pino({
mixin() {
const ctx = trace.getActiveSpan()?.spanContext();
return ctx ? { trace_id: ctx.traceId, span_id: ctx.spanId } : {};
},
redact: ['customer.email', 'customer.phone', 'req.headers.authorization'],
});
interface Order { id: string; channel: 'web' | 'app' | 'kiosk'; total: number; items: unknown[] }
export async function placeOrder(order: Order, save: (o: Order) => Promise<void>) {
return tracer.startActiveSpan('order.place', async (span) => {
try {
span.setAttributes({ 'order.channel': order.channel, 'order.items': order.items.length });
await save(order);
// Attributes on metrics = dimensions: keep them low-cardinality (never orderId or userId).
ordersPlaced.add(1, { channel: order.channel });
orderValue.record(order.total, { channel: order.channel });
log.info({ orderId: order.id, total: order.total }, 'order placed');
} catch (err) {
span.recordException(err as Error);
span.setStatus({ code: SpanStatusCode.ERROR });
log.error({ err, orderId: order.id }, 'order failed');
throw err;
} finally {
span.end();
}
});
}// CloudWatch Embedded Metric Format: a structured log line that CloudWatch Logs turns into
// a metric – no PutMetricData calls, works on Lambda and in containers with the awslogs driver.
export function emitMetric(name: string, value: number, unit: 'Count' | 'Milliseconds', dims: Record<string, string>) {
console.log(JSON.stringify({
_aws: {
Timestamp: Date.now(),
CloudWatchMetrics: [{ Namespace: 'Pierogi', Dimensions: [Object.keys(dims)], Metrics: [{ Name: name, Unit: unit }] }],
},
...dims,
[name]: value,
}));
}
emitMetric('KitchenTicketPrinted', 1, 'Count', { Service: 'kitchen-worker', Channel: 'web' });- Automatic instrumentation creates spans for HTTP, Express,
pg, Redis/Valkey and AWS SDK calls – with no code changes. You add custom spans where business logic matters (order.place). - A collector as a sidecar (AWS Distro for OpenTelemetry or the CloudWatch agent) accepts OTLP on
localhost:4318and sends traces to X-Ray and metrics to CloudWatch. The application knows no AWS telemetry APIs, and switching vendors means changing the collector config. - The X-Ray SDKs have been in maintenance mode since 25 February 2026, and support ends on 25 February 2027. The X-Ray service itself continues and accepts OpenTelemetry data – instrument new projects with OTel from the start.
- Cardinality is the most expensive metrics mistake: every unique combination of dimensions is a separate metric billed monthly.
channel(3 values) – yes;orderIdoruserId– never. The details of a single order belong in logs and traces.
The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Logs: structure, retention and cost
- Step 2. Alarms and a dashboard in CDK
- Step 3. Budgets, cost anomalies and tags
- Where the money goes
- Discounts: Savings Plans, Spot and Graviton
- Step 4. A weekly report from the CLI
- Common mistakes
- Test yourself
- What's next