Lesson 256 of 296
DynamoDB, CloudWatch and ECS/Fargate
What you will learn
- Using DynamoDB from Node.js
- CloudWatch: metrics, logs, alarms and dashboards
- Observability: logs, metrics and traces
- ECS and Fargate: running containers on AWS
- Task definitions, services and deployments
On this page
DynamoDB from Node.js
Lesson 229 explained DynamoDB's design. With the AWS SDK v3 document client, you work with plain JavaScript objects:
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, QueryCommand } from "@aws-sdk/lib-dynamodb";
const client = DynamoDBDocumentClient.from(new DynamoDBClient({ region: "eu-west-2" }));
const TABLE = "jobprep";
export async function saveOrder(customerId: string, orderId: string, isoDate: string, totalPence: number) {
await client.send(
new PutCommand({
TableName: TABLE,
Item: { PK: `CUSTOMER#${customerId}`, SK: `ORDER#${isoDate}#${orderId}`, totalPence, status: "pending" },
ConditionExpression: "attribute_not_exists(PK)"
})
);
}
export async function ordersInMonth(customerId: string, yearMonth: string) {
const result = await client.send(
new QueryCommand({
TableName: TABLE,
KeyConditionExpression: "PK = :pk AND begins_with(SK, :prefix)",
ExpressionAttributeValues: { ":pk": `CUSTOMER#${customerId}`, ":prefix": `ORDER#${yearMonth}` },
ScanIndexForward: false
})
);
return result.Items ?? [];
}ConditionExpression: "attribute_not_exists(PK)"makes the write fail if the item already exists (an idempotent create).begins_withon the sort key returns one customer's orders for a month, newest first withScanIndexForward: false.- Results are paginated: if
LastEvaluatedKeyis returned, pass it asExclusiveStartKeyfor the next page.
CloudWatch
Amazon CloudWatch collects metrics and logs from AWS services and your applications.
| Feature | Use |
|---|---|
| Metrics | Numbers over time: CPU, request count, Lambda errors and duration, SQS queue age, RDS connections, and custom metrics you publish |
| Logs | Lambda and ECS output goes to log groups automatically; set retention (logs are kept forever by default, which costs money) |
| Logs Insights | Query logs: fields @timestamp, level, msg | filter level = "error" | sort @timestamp desc |
| Alarms | Trigger when a metric crosses a threshold: notify via SNS (email, Slack, PagerDuty), scale out, or roll back a deployment |
| Dashboards | Graphs of key metrics in one place |
| Synthetics / RUM | Scripted checks of your site / real user monitoring |
Write structured logs (JSON) so they can be queried: {"level":"error","msg":"payment failed","orderId":"101","requestId":"..."}. Libraries: pino, Powertools for AWS Lambda.
Observability
The three pillars:
| Pillar | Answers |
|---|---|
| Logs | What exactly happened in this request? |
| Metrics | How is the system behaving overall? (rates, errors, durations) |
| Traces | Where did the time go across services for one request? (AWS X-Ray, or OpenTelemetry sending to any back end) |
Useful alarm signals: the four golden signals (latency, traffic, errors, saturation), plus queue age and DLQ size. Alert on symptoms users feel (error rate, latency), not every CPU spike, to avoid alert fatigue.
ECS and Fargate
ECS (Elastic Container Service) runs Docker containers on AWS.
| Concept | Meaning |
|---|---|
| Cluster | A logical group for running containers |
| Task definition | The blueprint: image, CPU and memory, ports, environment variables, secrets, log configuration, IAM roles |
| Task | A running instance of a task definition (one or more containers) |
| Service | Keeps the desired number of tasks running, replaces failed ones, registers them with a load balancer, and performs rolling deployments |
Launch types:
- Fargate: serverless containers. You do not manage servers; you pay for the task's CPU and memory. The usual choice.
- EC2 launch type: tasks run on EC2 instances you manage (more control, can be cheaper at large steady scale, GPUs).
A typical production set-up:
Route 53 → CloudFront (optional) → Application Load Balancer (public subnets)
→ ECS service on Fargate: 2+ tasks across 2 AZs (private subnets)
→ RDS PostgreSQL Multi-AZ, ElastiCache Redis, S3, SQS (private subnets / VPC endpoints)
Images in ECR, secrets from Secrets Manager, logs to CloudWatch, auto scaling on CPU or requests per targetDeployments: push a new image to ECR, register a new task definition revision, update the service; ECS starts new tasks, waits for load balancer health checks, then drains and stops old ones. The deployment circuit breaker can roll back automatically if new tasks keep failing. Graceful shutdown matters: ECS sends SIGTERM, waits (stopTimeout, 30 seconds by default), then SIGKILL (Lesson 193).
Alternatives: App Runner (simplest: image or source in, HTTPS URL out), EKS (managed Kubernetes, more power and complexity), Elastic Beanstalk, or other clouds' equivalents (Google Cloud Run, Azure Container Apps).
How to say it in an interview
"With DynamoDB I use the SDK v3 document client, conditional writes for idempotent creates or optimistic locking, and Query on the partition key with sort key conditions, handling pagination with LastEvaluatedKey. CloudWatch collects metrics and logs; I write structured JSON logs, set log retention, query with Logs Insights, and alarm on user-facing symptoms like error rate, latency and queue age, with traces from X-Ray or OpenTelemetry. For containers I use ECS on Fargate: a task definition describes the image, resources, secrets, logs and roles, and a service keeps the desired tasks running behind an Application Load Balancer across two AZs, doing rolling deployments with health checks and an automatic rollback circuit breaker."
Key words
| Word | Meaning |
|---|---|
| Document client | DynamoDB SDK layer using plain JavaScript objects |
| Conditional write | A write that succeeds only if a condition holds |
| CloudWatch metric / log group / alarm | Measurements / log storage / threshold alerts |
| Structured logging | Logs as JSON fields |
| Trace | The path and timing of one request across services |
| OpenTelemetry | An open standard for traces, metrics and logs |
| ECS task definition / task / service | Blueprint / running copy / keeps copies running |
| Fargate | Serverless compute for containers |
| ECR | AWS's container image registry |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.