跳到正文
DEV Community· Harshit Agarwal·· 1 小時前AI 評分57

FamCare 回顧三次生產事故及其留下的基礎設施改進

Three Outages and the Infrastructure They Left Behind

AI 導讀

FamCare 作者回顧其 AWS 生產環境中的三次事故,整理出根因及相應防護措施。事故涉及 ECS 服務更新受阻、資料庫連線池耗盡,以及 Terraform 設定的較大記憶體未部署到實際任務,導致容器遭終止。文章提出由資源所屬服務管理刪除、為連線取得設限、按真正飽和的資源擴容,並明確劃分 Terraform 與 CI 的管理範圍。

正文

Originally published at aharshit123456.space.

Our API stopped answering, and every health check said it was fine. The load balancer saw a healthy target, the database looked healthy, and yet nobody could log in. That was the second of three incidents in our first few months of running production from code instead of the AWS console. This post tells all three: the symptom, the wrong theories, the real cause, and the guardrail each one left behind, plus the postmortem format that grew out of them.

FamCare is an in-home care marketplace in India: families book trained caregivers for babies and elders by the hour from an app. Behind the customer app, the caregiver app and an admin panel sits one Python API on AWS ECS Fargate, a scheduler service, an Aurora Serverless v2 Postgres database and a single load balancer.

  • ~8 min of outage caused by the recovery, not the original mistake
  • 3 times the same symptom appeared in four days
  • 5 → 25 connections in the API's database pool, before and after

From console clicks to a plan you can trust

Production was first built by hand in the console, with no record of how it was configured. In July 2026 I mirrored it into Terraform without changing anything, then built a separate staging environment beside it (A Care Marketplace on One Boring Backend covers that import).

Terraform keeps a state file: its record of which real resources it manages and what it last knew about them. Each plan compares your code, that state and what AWS reports right now. When they disagree, that's drift, and drift is only harmless if every disagreement can be explained. Our rules all exist to keep plan honest:

  • State lives remotely, in a versioned S3 bucket with a DynamoDB lock, so two people can never apply at once.
  • On production, 0 to destroy is the norm, and any must be replaced on a live service or database is a stop sign.
  • apply exiting 0 is not success. ECS can crash-loop after a clean apply, so you check the running tasks and the health endpoint.
  • No one-off console edits, because the next plan won't be able to explain them.

That last rule is the one we broke most. Each story below is what happened when we did.

Apps + admin → Load balancer path rules split prod and staging → ECS cluster API (min 2 tasks), scheduler, monitor, Prometheus + Grafana → Aurora Serverless v2 timeouts in the parameter group

CI builds images, registers task definitions → Terraform network, services, scaling, alarms → CloudWatch alarms + EventBridge rules → One alerts topic

Fig. 1 — the setup today. CI owns what runs inside each container; Terraform owns everything around it. Staging has its own cluster and private database and shares only the network and load balancer.

July console → Terraform → 1–2 Aug a service ECS wouldn't update → 6–9 Aug connection pool stuck three times → late Aug self-healing scrape targets, cost fixes → 2 Oct OOM kills from a size that never shipped

Fig. 2 — the incidents (filled) and the work between them, 2026.

Each story is told the way it looked at the time: the first sign of trouble, the terminal, the theory that failed, and the output that finally explained it. Commands are trimmed, identifiers are replaced with placeholders, where the written record kept only a summary of an output, the summary is what you see, and a few command lines are reconstructed around results the postmortems recorded.

Don't delete what another service owns

Service discovery is how one service finds another when their addresses keep changing. On ECS, every deploy replaces tasks, and every new task gets a new private IP. I was adding a private Prometheus and Grafana, and I wanted Prometheus to find the API by name so that deploys wouldn't break scraping.

I chose ECS Service Connect, which registers services in AWS Cloud Map and gives them internal names. My first attempt used Cloud Map's HTTP namespace type, which publishes no DNS records, so Prometheus's lookups found nothing. The fix seemed simple: swap it for a private DNS namespace. Terraform disagreed.

# terraform + aws cli · prod · 01:36
$ terraform apply
… replacing the HTTP namespace with a private DNS namespace …
Error: … ResourceInUse
… two Cloud Map services are still registered in the old namespace
$ aws servicediscovery get-service --id srv-xxxx
…
    "Description": "Managed by arn:aws:ecs:…",
…
$ aws servicediscovery deregister-instance --service-id srv-xxxx --instance-id <instance>
$ aws servicediscovery delete-service --id srv-xxxx
… same again for the second service, srv-yyyy …

The answer was on the screen. The CLI output said ECS managed those services. I deleted both by hand anyway, to unblock Terraform, and the namespace swap went through.

Every fix is an update, and updates are blocked

Half an hour later, the next update to the API service failed. So did everything I tried to fix it.

# incident · 2 Aug, 02:07

Me: Updates to the API service fail and roll back. The running task is fine.

Me: New task definition with the right namespace: rolled back.

Me: Forced redeploy: rolled back. Turning Service Connect off on the service.

Me: Rolled back. Same error every time. Customers are still being served.

# aws cli · prod · 02:07–02:39
$ aws ecs update-service --cluster <cluster> --service <service> --force-new-deployment
…
$ aws ecs describe-services --cluster <cluster> --services <service> \
    --query 'services[0].events[0].message'
"ECS deployment failed Service deployment rolled back because of invalid
 networking configuration. Cloud Map service does not exist."
$ aws ecs update-service --cluster <cluster> --service <service> \
    --service-connect-configuration enabled=false
… rolled back, same message
$ terraform destroy -target=<api ecs service>
… same message: the scale-to-zero step before a delete is itself an update
… side effect: the service's autoscaling target and policy were destroyed

As far as we could tell, ECS validates the service against its old Cloud Map reference on every update, including the update that tries to remove that reference. There was no supported way to update the service out of this state.

The targeted destroy added a small mess of its own: it failed on the service but succeeded on the service's autoscaling, leaving the API pinned at one task. A targeted apply on just the autoscaling resources put it back.

For about three hours this cost customers nothing. ECS checks a change before applying it, so every failed fix was a safe no-op and the old task kept serving. But nothing could be deployed, and the deploy pipeline failed at the same step.

Deploy pipeline fails at "update service" → API service every update rolls back → Cloud Map service deleted by hand, still referenced

Apps + admin → Load balancer → Target group 0 healthy targets for ~8 min → Old service DRAINING name still taken

Fig. 3 — the blast radius in two stages. Filled nodes failed. For three hours only the deploy path was broken; after the forced delete, the target group had nothing behind it. The scheduler and the monitoring stack were never affected.

The way out, and the eight minutes it cost

The one call that skipped the stale check was delete-service --force. The plan was to delete the stuck service and immediately create an identical one. What I didn't check first was how long a deleted service takes to really go away.

# aws cli · prod · 02:45
$ aws ecs delete-service --cluster <cluster> --service <service> --force
    "status": "DRAINING",
$ aws ecs create-service --cluster <cluster> --service-name <service> …
… Create service is not idempotent.
… retried for several minutes; the old service stays DRAINING …
$ aws elbv2 describe-target-health --target-group-arn <api-tg>
… no healthy targets
$ aws ecs create-service --cluster <cluster> --service-name <service>-restore …
… task healthy in ~30 s …
$ curl -s -o /dev/null -w '%{http_code}\n' https://<api-host>/health
200

# incident · 2 Aug, 02:45

Me: Forced delete worked. Service is DRAINING.

Me: Recreating under the same name is refused. The API has zero running tasks.

Monitor: (nothing: no alarm watched for an empty target group)

Me: Replacement up under a temporary name. Health check returns 200.

Me: [RESOLVED] Old name freed. Real service recreated, temporary one deleted.

deploys blocked, customers unaffected: ~3 h (every failed fix was rejected before it touched the running task)

API with no running task: ~8 min (caused by the recovery, not by the original mistake)

Once the original service reached INACTIVE, I created the real one under its proper name, let it run beside the temporary service behind the same target group, then deleted the temporary one. Terraform picked it up without any state surgery, because an ECS service's ARN is determined by its cluster and name, and the next apply cleanly re-attached autoscaling and Service Connect.

Nobody was paged during those eight minutes. The outage was found only because I was watching describe-services and curling the health endpoint after every step. The same day, an alarm on the API's target group went in. Note the last line, which makes silence count as failure:

metric_name         = "HealthyHostCount"
statistic           = "Minimum"
period              = 60
evaluation_periods  = 2
threshold           = 1
comparison_operator = "LessThanThreshold"
treat_missing_data  = "breaching"

The trigger was deleting two resources by hand. The root cause was deleting a resource without checking what still referenced it, and doing it outside the service that owned it. Those are different things to fix: the first is one command, the second is a habit.

Runbook change: before deleting anything another AWS service created, check who owns it and release it through that owner. Before a forced delete, assume the name stays taken for minutes, and recreate under a temporary name.

Service Connect isn't DNS

The private DNS namespace didn't fix Prometheus either. From inside the monitoring task:

# monitoring task + aws cli · prod
$ nslookup <api-name>.<namespace>
… NXDOMAIN
$ aws route53 list-resource-record-sets --hosted-zone-id <zone> \
    --query 'ResourceRecordSets[].Type'
[ "NS", "SOA" ]
… no address records at all

Service Connect doesn't publish ordinary DNS. It works through a proxy sidecar on participating containers, so a general tool like Prometheus can't use it. The migration I broke production for could never have worked.

What works now is a Lambda that finds the API's task IPs every minute and writes them into Prometheus's config in SSM. The first version then called Prometheus's reload endpoint directly, and it looked like success:

# monitoring task · prod
$ curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:9090/-/reload
200
… active targets: still the old task IP

Reload only re-reads the file on disk, and nothing had changed the file. A small sidecar now polls SSM every 30 seconds, rewrites the file and reloads Prometheus locally. The acceptance test was to force two API task replacements and watch Prometheus follow on its own. A 200 from an endpoint is not proof that anything changed.

The pool that kept filling up

This is the incident from the opening. It's worth explaining one concept first.

A connection pool keeps a few open database connections and lends them to requests. A request acquires one, runs its queries and gives it back. If connections aren't given back, or are borrowed for too long, new requests wait in a queue for a free one. Postgres has a related state called idle in transaction: a session has opened a transaction and is holding it, but isn't running a query. Postgres can't tell that apart from a slow client, so by default it waits.

Our API's pool had a maximum of 5 connections, shared by all three apps.

Everything is green except logins

# incident · 6 Aug, ~11:10

Me: Reports that the APIs may be down. Login and OTP requests just spin.

Me: Every dashboard says healthy. Checking each layer.

# aws cli + curl · prod
$ curl -s -o /dev/null -w '%{http_code}\n' https://<api-host>/health
200
$ aws elbv2 describe-target-health --target-group-arn <api-tg> \
    --query 'TargetHealthDescriptions[].TargetHealth.State'
[ "healthy" ]
$ aws rds describe-db-clusters --db-cluster-identifier <db> --query 'DBClusters[0].Status'
"available"
… low CPU, no events, firewall showing no blocks on real traffic …
$ curl -s https://<api-host>/health/deep
{"status":"unhealthy","db":"unreachable"}     # HTTP 503
$ curl -s -X POST https://<api-host>/<otp-send> …
… hangs until the client gives up

The shallow health check never touches the database, and neither does the load balancer's. The deep one does a bounded SELECT 1 through the pool, with a three-second limit on getting a connection, and it couldn't get one. Meanwhile the database's own connection count sat flat.

database connections, in every occurrence: 6 (flat, not climbing: one task, a pool of 5, nothing free to lend)

The first theory was that something kept restarting the service. The audit log showed a run of forced redeployments:

# aws cli · prod
$ aws cloudtrail lookup-events \
    --lookup-attributes AttributeKey=EventName,AttributeValue=UpdateService
… several force-new-deployment calls in the window …
… each from a separate CI run, different source IPs: ordinary deploys
ruled out
$ aws ecs update-service --cluster <cluster> --service <service> --force-new-deployment
… new task running …
$ curl -s -o /dev/null -w '%{http_code}\n' https://<api-host>/health/deep
200

A fresh task meant a fresh pool, and that ended the impact. It explained nothing, though.

Customer app caregiver app admin panel → Load balancer target healthy → API task shallow /health 200 → Pool of 5 no free connection → Aurora available, low CPU

Autoscaling watches CPU, which stayed idle → stays at 1 task

Fig. 4 — where the pool incident lived. Filled nodes failed. Everything the standard health checks looked at stayed green; the only broken part sat between the API and the database, and the scaler was watching the wrong signal.

Timeouts at every layer

After the redeploy, we looked for what could hold a connection forever, and found nothing bounding it at either layer. The app's transaction wrapper had no timeout. The database had no statement_timeout, and its idle-in-transaction timeout was Aurora's default of 24 hours. We added both:

# Database-level backstop, set above the app's own 15-second timeout
# so the app's timeout fires first and this is the last resort.
statement_timeout_ms                   = 20000  # 20s
idle_in_transaction_session_timeout_ms = 300000 # 5min

We also put an alarm on repeated deep-health 503s. About four hours later, an alarm fired:

# incident · 6 Aug, ~16:53

Monitor: [ALARM] Load balancer 5xx count 60 in one period, threshold 5

Me: Deep health is 503 again. Connections flat at 6. Same signature.

Me: Checking whether this morning's fixes are actually on the stuck task.

# aws cli · prod
$ aws rds describe-db-cluster-parameters --db-cluster-parameter-group-name <params> \
    --query "Parameters[?ParameterName=='statement_timeout' || ParameterName=='idle_in_transaction_session_timeout'].[ParameterName,ParameterValue]"
statement_timeout                     20000
idle_in_transaction_session_timeout   300000
$ aws ecs describe-task-definition --task-definition <service> --query '…image'
… the running image already has the transaction timeout
both fixes live; pool stuck anyway

Both fixes were real, and neither covered the path that was actually holding connections. The wrapper wasn't the only way into the pool:

# backend repo
$ grep -rnE 'db\.pool\.(fetch|fetchval|fetchrow|execute)\(' --include='*.py' . | wc -l
     231
… none of them passes timeout=, and asyncpg's default is no limit

direct pool calls that bypassed the wrapper: 231 (each one free to hold a connection for as long as it liked)

And statement_timeout doesn't help when a connection is held while Python waits on something else, because there's no running statement to kill. A database timeout is a backstop, not a substitute for one in the app.

I patched those four methods once, at pool creation, so every call defaulted to 15 seconds. It passed every unit test, then staging refused to start:

# container logs · staging
$ aws logs tail /ecs/<service> --since 15m
AttributeError: 'Pool' object attribute 'fetch' is read-only
RuntimeError: Failed to connect to PostgreSQL ...
Application startup failed. Exiting.
$ aws ecs describe-tasks --cluster <staging-cluster> --tasks <task-a> <task-b> \
    --query 'tasks[].containers[0].exitCode'
[ 3, 3 ]

The real asyncpg.Pool uses __slots__, so you can't assign methods onto an instance, and the tests had mocked the pool with plain objects that allowed it. Production never ran the broken image: its new task failed to become healthy, so ECS kept the old one serving. A thin proxy class fixed it, and the tests now use a fake pool that enforces __slots__, so this kind of bug fails in CI.

The evidence that had been there all along

Timeouts bound the damage of a stuck call. They don't say what was slow. The load balancer had been writing access logs to S3 the whole time, and nobody had opened them.

# alb access logs · recurrence window
$ aws s3 cp s3://<alb-log-bucket>/<prefix>/ ./alb-logs --recursive
$ zcat alb-logs/*.gz | awk '{print $7, $13, $14}' | sort -rn | head
14.469 GET <availability endpoint>
10.205 GET <availability endpoint>
… several more at 3–5 s, same endpoint, all in the ten minutes before the 503s
… an unpaginated admin list at 3.8–5.3 s (secondary)

one availability request, just before the pool stuck: 14.5 s (from a data source that needed no new infrastructure, only someone to read it)

Inside a loop over services and time slots, that endpoint borrowed a fresh pool connection on every iteration. That's dozens of acquire-and-release cycles per request through a five-connection pool. It now uses one connection per service, and that connection is deliberately not held across an external HTTP call. Holding a pool connection during network I/O was exactly the bug behind an earlier deadlock.

Later, a teammate found that our timeout guarded the wrong half. asyncpg's convenience methods pass the timeout to the query, but call acquire() without one, so under saturation requests still queued forever. They bounded acquire() too, which turns pool exhaustion into fast, visible errors instead of silent hangs.

Scale on the signal that's actually saturated

Three days later, with every fix live, the symptom came back.

# incident · 9 Aug, ~10:23

Me: Same signature since about 08:00: connections pinned at 6, CPU spiking. Every fix is live.

Me: Deep health is back to 200 on its own. Nothing to restart this time.

Me: Different question: why didn't autoscaling add a task?

# aws cli · prod
$ aws ecs describe-services --cluster <cluster> --services <service> \
    --query 'services[0].[desiredCount,runningCount]'
[ 1, 1 ]
$ aws application-autoscaling describe-scaling-policies --service-namespace ecs …
… one policy: target tracking on task CPU at 60%, min 1, max 10
$ aws application-autoscaling describe-scaling-activities --service-namespace ecs …
… last scale-out: the evening of the first outage, three days earlier

It tracked CPU, and an API that's waiting on its database has idle CPU. The bottleneck was connections, and nothing was scaling on connections.

We added a second scale-out trigger on the database's own connection count, and raised the API's minimum from one task to two. A teammate had separately found the case for the second change: with one task, every deploy left a moment with no healthy target.

requests failed in a single second during one rollout: 84 (all 502s with no target: one task, being replaced)

We also raised the database's capacity ceiling. Aurora Serverless v2 bills for capacity actually used, so a higher ceiling costs nothing until it's needed. It also had to come before a bigger pool, because more connections against a capped database makes things worse, not better. Then the pool went from 5 to 25.

The other change was evidence. Query-level telemetry had been on the list since the first outage and was still off:

# aws cli · prod
$ aws rds modify-db-instance --db-instance-identifier <instance> \
    --enable-performance-insights --performance-insights-retention-period 7 --apply-immediately
$ aws rds describe-db-instances --db-instance-identifier <instance> \
    --query 'DBInstances[0].[PerformanceInsightsEnabled,DBInstanceStatus]'
[ true, "available" ]
… later that day, top SQL: ordinary reads; top waits: CPU, Client:ClientRead
… nothing from the incident window: it can't record the past

Three fixes for one symptom means the constraint is wrong

Each fix was real and verified. But the first postmortem had already listed the two things that mattered: raise or measure the pool size, and turn on query-level evidence. Both stayed open while we hunted for more bad call sites, so we investigated three times with worse evidence than was available almost for free.

Note: The root cause in the rewritten postmortem isn't a line of code. Each recurrence was treated as a new bug to find, instead of as evidence that the constraint itself (a 5-connection pool with almost no margin) was wrong.

Runbook change: before investigating a recurrence, read the last postmortem's open items. If the same signature survives three fixes, stop patching call sites and question the limit.

The memory upgrade that never shipped

During the pool work, a plan nearly bit us:

# terraform · prod · 9 Aug
$ terraform plan
…
  ~ task_definition = "<api>:480" -> "<api>:472"
  ~ task_definition = "<scheduler>:449" -> "<scheduler>:441"
… plan discarded, nothing applied …
$ terraform plan     # after ignore_changes = [desired_count, task_definition]
Plan: 2 to add, 1 to change, 0 to destroy.

It wanted to roll the API back to a task definition (ECS's versioned spec of image, environment and resources) eight revisions old, as a side effect of an unrelated scaling change. Our CI registers a new revision on every deploy, so Terraform's memory of it was stale. We told Terraform to ignore the task definition on the service, and the rollback was avoided.

Two months later, that fix came back to bite.

# incident · 2 Oct

Me: Admin panel and apps getting 502s and 504s.

Me: API tasks keep getting replaced. Containers exit with 137.

# aws cli + curl · prod
$ aws ecs describe-tasks --cluster <cluster> --tasks <stopped-task> \
    --query 'tasks[0].containers[0].exitCode'
137     # killed for exceeding its memory limit
$ curl -s -o /dev/null -w '%{size_download} bytes in %{time_total}s\n' \
    https://<api-host>/<daily-reports-list>
… ≈27 MB, 9–15 s per call

The trigger was a reporting feature: each day's stored report embedded the previous day's report, which embedded the day before that. The list endpoint had grown to return 27 MB, and regenerating reports loaded a year of them into Python at once. Slimming the payloads in SQL fixed the response.

daily-reports list response: 27 MB → ~0.5 MB (nested history stripped in SQL, month and year totals aggregated in the database)

That explained the spike, not the ceiling. The container should have had far more room, because a month earlier I had doubled the API's CPU and memory in Terraform:

# terraform repo vs aws · prod
$ grep -nE '^\s*(cpu|memory)\s*=' environments/prod/main.tf
… API service:
  cpu    = 1024
  memory = 2048
$ aws ecs describe-task-definition --task-definition <api> \
    --query 'taskDefinition.[cpu, containerDefinitions[0].memory]'
[ "512", 600 ]

API memory: what ran vs what the code said: 600 MB vs 2,048 MB (the upgrade sat in Terraform for a month and never reached production)

The service ignored task definition changes (our fix from August), and CI built each deploy by cloning the running task definition. Our fix for one kind of drift had quietly created another.

Terraform 1 vCPU / 2 GB ignored by the service → CI deploy clones the running task definition → API task 0.5 vCPU / 600 MB killed, exit 137 → Load balancer 502 / 504 → Admin + apps

Fig. 5 — how a size change got lost. Filled nodes failed: CI copied the small live size forward on every deploy, the container ran out of memory, and the load balancer turned each kill into 502s and 504s. Terraform's larger size never entered the chain.

The lasting fix was to make ownership explicit instead of implicit:

Terraform owns CI owns
Network, load balancer, services, scaling, alarms, permissions Image, environment, secrets, CPU and memory
The first revision of each task definition Every revision after that

A module option now makes Terraform create a task definition once and never touch its containers, CPU or memory again, and the deploy pipeline sets the size it deploys. Moving to two server processes per task also meant in-memory event fan-out stopped reaching browsers connected to the other process, so those events now go through Redis pub/sub.

The incident left three alarms on one topic, each for a different question. An EventBridge rule on any container stopped for running out of memory tells us the cause. Memory at 85% is the early warning. And the load balancer's own 5xx count, as opposed to the app's, shows when customers are affected.

Runbook change: before trusting a size in Terraform, compare it with the task definition that is actually running.

Guardrails can misfire too

The connection-based scaling trigger first fired at 5 connections, a number taken from a snapshot during the incident. In normal running, the API, the scheduler and an internal agent service together held more than that. So the alarm fired constantly, fought the CPU policy, and pinned the API at its maximum of 10 tasks while CPU sat around 4 or 5 percent. We raised it, and raised it again with a wider window as traffic grew. The second raise was made in the console, against our own rule. When it was brought back into Terraform, the only record of why was the alarm's own description, so that reasoning now sits in a comment next to the value.

Size a guardrail against the steady-state baseline, not the worst minute of the incident, and write the reason down where the next person changing it will see it.

Reconciling with reality pays in money too. AWS Config was recording every resource change with nothing reading the data, so we switched the recorder off. VPC flow logs showed S3 was the heaviest traffic through our NAT gateway, and a free S3 gateway endpoint took it off the per-gigabyte NAT charge.

Writing it down: trigger, root cause and luck

After the first incident, I wrote down how our postmortems should be structured. It starts from Google SRE's skeleton, with a stricter root-cause section:

  • Impact, with phases kept apart. Three stuck hours with no customer impact are not eight minutes of outage.
  • Root cause by five whys, ending in something you can fix. "A mistake was made" doesn't count.
  • Contributing factors under technology, process and people, written as process gaps, never as blame.
  • Trigger, separate from root cause. The trigger started it; the root cause is why it could do damage.
  • Resolution, including what didn't work, because that's what the next responder searches for.
  • Detection. If a person noticed before an alarm did, that is a finding.
  • Where we got lucky. The section people skip, and usually where the next incident shows up first.
  • A timeline captured during the incident, with exact commands and error text.

The pool incident added two rules. When a recurrence proves the conclusion wrong, rewrite the document rather than appending another addendum. And before investigating a recurrence, read the last postmortem's open items. In our case they already held the answer.

Two teammates built the same thinking into a read-only booking investigator for our operations team. It answers "why did no caregiver come?" in three layers (symptom, direct cause in the records, root cause), and every fact it states must come from a tool result.

One debugging habit came out of all this too. While rolling out the monitoring stack, the real errors were only in each failing container's own log stream: an image that didn't exist, a missing log group, and images whose built-in entrypoint swallowed the command we passed. The stop reason and exit code never showed them. Now we read the failing container's logs on the first failure, before proposing the next fix.

What I'd keep from all this

  • Separate the trigger from the root cause. "I deleted two resources" is the trigger; "we delete things without checking what references them" is the root cause, and only fixing that prevents the next one.
  • Put timeouts at every layer, and make the app's fire first. Bound the query, bound the wait for a connection, and keep a database-side backstop for whatever slips past both.
  • Autoscale on the resource that actually saturates. An I/O-bound service looks idle on CPU while it falls over. Know your bottleneck and scale on it.
  • Decide who owns each attribute. When CI and infrastructure-as-code both touch the same resource, write down which one owns what, or one of them will silently undo the other.
  • When one symptom survives several real fixes, question the constraint. The next call-site patch is rarely the answer.
  • Every incident should leave a guardrail, sized against normal traffic. An alarm tuned to the worst minute of an outage becomes the next outage.

Stack in this post: Terraform, AWS ECS Fargate, Application Load Balancer, Aurora Serverless v2 (Postgres), CloudWatch, EventBridge, SNS, Lambda, SSM Parameter Store, Cloud Map, Prometheus, Grafana, Python, FastAPI, asyncpg. Figures come from the infrastructure repository, its written postmortems and the backend's history, July to November 2026.

More from Building FamCare

來源:DEV Community · dev.to