Ravindra BagaleCourses & study guides मराठी Track your progress

Strangler Fig Pattern: Migrate a Monolith to Serverless Step by Step

A banyan (strangler fig) grows around an old tree until the old trunk can come down. In software you peel one route at a time from a monolith to API Gateway + Lambda. Users keep one URL. You avoid a big-bang rewrite weekend that never ends.

What you'll learn in this chapter

  • Explain strangler fig with a plant story
  • Peel one HTTP route behind a facade
  • Coexist monolith and Lambda safely
  • Plan rollback per route
  • Know when NOT to strangle yet

1. Everyday example: city bus ticket counter

Omar in Amman (JOD) modernizes a gov portal. Citizens still hit portal.gov.jo. Week 1 only /forms/birth-cert goes to Lambda; everything else hits the old Tomcat box. Next sprint /forms/marriage. If Lambda misbehaves, flip that one path back. That is strangler fig — not rewriting the whole portal in a holiday weekend.

Edge skills: API Gateway. Pattern labs like REST API project and notes app show greenfield APIs — strangler adds the coexistence story.

2. Why strangle?

Why do we need this?

Big-bang rewrites slip. Risk concentrates in one cutover. Strangling spreads risk across sprints, proves each peel in production, and keeps revenue flowing in INR, USD, or EUR while you migrate.

What is it?

Strangler fig pattern = put a facade (often API Gateway, ALB, or reverse proxy) in front of the monolith; route selected paths to new serverless services; retire old paths when unused.

3. Vertical diagram

Client -> Facade -> Monolith OR LambdaFeature flag or route table chooses branch
Never dual-write without an idempotency story
Client (same hostname) Facade: API Gateway / ALBroute table / weighted target Legacy monolithTomcat / Django / .NET New Lambda+ DynamoDB / HTTP Shared data? careful sync plan Peel routes until monolith shrinks
Strangler: one facade, two backends, gradual peel.

4. How: peel one route

How to do it (step by step)

  1. Inventory routes by traffic and pain (errors, deploys).
  2. Pick a leaf route with clear input/output (PDF form, not checkout core).
  3. Put facade in front if not already (custom domain on API Gateway or ALB rules).
  4. Implement Lambda + data access; contract tests vs old responses.
  5. Shadow traffic or 1% canary; compare status and body hashes.
  6. Raise to 100%; monitor; keep rollback switch one click.
  7. Delete unused monolith code only after metrics prove zero hits.

5. Per-concept commands

List HTTP API routes

aws apigatewayv2 get-routes --region ap-south-1 --api-id "$API_ID" \
  --query 'Items[].{R:RouteKey,T:Target}' --output table

Meaning: Shows which paths already point at integrations (Lambda vs HTTP proxy).

ALB listener rules (if facade is ALB)

aws elbv2 describe-rules --region ap-south-1 --listener-arn "$LISTENER_ARN" \
  --query 'Rules[].{P:Priority,C:Conditions[0].PathPatternConfig.Values[0]}' --output table

Meaning: Path rules are your peel map — document before changing priority.

Compare canary error rates

aws cloudwatch get-metric-statistics --region ap-south-1 \
  --namespace AWS/Lambda --metric-name Errors --dimensions Name=FunctionName,Value=birth-cert-api \
  --start-time $(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%S) --end-time $(date -u +%Y-%m-%dT%H:%M:%S) \
  --period 300 --statistics Sum

Meaning: If canary Errors rise vs baseline, flip route back before 100%.

Old host still getting peeled path?

# On monolith host (example): count hits to migrated path last hour
sudo grep '/forms/birth-cert' /var/log/nginx/access.log | tail -20

Meaning: After 100% peel, this should go quiet — proves facade owns the path.

6. Data coexistence

StrategyUse whenRisk
Read old DB from LambdaEarly peels; DB is source of truthCoupling; connection limits
Dual write old+newShort migration windowsPartial failure; need saga-like care
Event sync / CDCNew read modelsLag; ordering
Freeze feature then cutTiny modulesProduct freeze cost

Ravindra Bagale's Tip

Prefer leaf peels that can keep reading the old database first. Dual-write only with idempotent keys.

7. When NOT to strangle yet

  • No facade possible (clients hardcode 20 IPs) — fix DNS/domain first.
  • Team cannot test contracts — you will ship silent breaks.
  • Regulated cut needs one audited switch — still can strangle behind flag with paperwork.
  • Module is a tangled ball with no route boundary — extract a seam first.

8. Industries

  • Gov (Omar, Amman, JOD): one PDF form per sprint.
  • Bank (Aisha, Lagos, NGN): peel statement download before core ledger.
  • Retail (Luis, Mexico City, MXN): peel store-finder API; POS stays.
  • EdTech (Diego, São Paulo, BRL): peel certificate PDF gen.
  • SaaS (Priya, Bengaluru, INR): peel /v1/webhooks receiver.

9. Lab

10. Lab - plan a peel (paper + gateway routes)

Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.

How to do it (step by step)

  1. Pick a real or sample monolith route list; mark leaf vs core.
  2. Write facade choice: HTTP API proxy vs ALB path rule.
  3. Define success metrics: p95, 5xx, business KPI.
  4. Write rollback steps in five bullets.
  5. Optional: create a lab HTTP API with two routes — one MOCK, one AWS_PROXY.

Cleanup (stop billing)

  1. Delete lab APIs and Lambda.
  2. Remove canary alarms you created.

11. Same pattern across industries

  • Fintech (Aisha, Lagos): payment webhooks → SQS → Lambda; never block the bank callback thread.
  • Ecommerce (Rohan, Pune): checkout API on API Gateway+Lambda; inventory fan-out on SNS.
  • Healthcare (Mei, Singapore): appointment SMS via SNS; PHI stays in DynamoDB with fine-grained IAM.
  • EdTech (Diego, São Paulo): nightly cleanup EventBridge → Lambda on student drafts.
  • Logistics (Fatima, Casablanca): package scan events on EventBridge bus; Step Functions for customs saga.
  • Media (Kenji, Osaka): S3 upload → Lambda thumbnails; fan-out to moderation + CDN invalidate.
  • SaaS multi-tenant (Priya, Bengaluru): Cognito groups + DynamoDB partition per tenant.
  • Gov portal (Omar, Amman): strangler fig — peel one PDF form route per sprint to Lambda.

12. Troubleshooting checklist

  1. Confirm region (ap-south-1 vs us-east-1 for CloudFront/ACM quirks).
  2. Check CloudWatch Logs for the function name and request id.
  3. Verify IAM execution role allows the API you call.
  4. For async: check DLQ depth and SQS age of oldest message.
  5. For APIs: curl -v and compare status, CORS headers, body.
  6. For workflows: open Step Functions execution event history.
  7. Re-read the linked deep chapter before reinventing a service.
  8. If cost spikes: check concurrency, retries, and provisioned capacity.

13. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
Facade 5xx but Lambda OKCheck integration timeout, payload size, auth on proxy.
Old and new both hit — double chargeSingle writer rule; feature flag; idempotency key.
CORS broke after peelGateway CORS vs monolith headers — unify.
Session cookie missing on Lambda pathMove auth to JWT/Cognito; sticky sessions fight serverless.
Canary 10% but all bad usersHash-stable routing by userId, not random per request.
Monolith still high CPU after peelsYou peeled low-traffic leaves — pick hot routes next.
Rollback forgot DNS TTLLower TTL before cutover; document.
Contract test only happy pathAdd 400/404/401 fixtures from production samples.
INR reports differ by 1 paiseDecimal/rounding parity in both backends.

14. FAQ

Q. Is strangler only for HTTP?

Common for HTTP; same idea for message consumers peeled off a worker box.

Q. API Gateway or ALB?

HTTP APIs for Lambda-heavy; ALB when mixing EC2/ECS/Lambda targets.

Q. How long should coexistence last?

Until metrics show zero legacy hits and on-call is calm — months is OK.

Q. What about shared DB?

Early peels read old DB; extract later with CDC/events.

Q. Link to API chapters?

API Gateway + REST project chapters — greenfield building blocks.

15. Interview Q&A (Beginner / Mid / Senior + MNC)

Q. Beginner: strangler fig?

Gradually replace monolith behind a facade.

Q. Beginner: facade?

Single entry that routes old vs new.

Q. Mid: first peel choice?

Leaf, high pain or clear boundary — not the ledger core.

Q. Mid: rollback?

Route switch back in facade; keep old code until proven.

Q. Senior: data dual-write?

Only with idempotency and clear primary; prefer read-old then CDC.

Q. MNC: audit?

Change ticket per route; metrics before/after; rollback drill.

16. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

One hostname, many peels. Flip one path, learn, repeat.

Ravindra Bagale's Tip (MR)

एक hostname, अनेक peels. एक path flip, शिका, पुन्हा.

Tip (HI)

एक होस्टनाम, रास्ते धीरे-धीरे: एक flip, सीखो, दोहराओ।

Try at home

  1. List 5 routes; mark leaf/core.
  2. Write rollback for one peel.

In short

  1. Start from a real story, then name the AWS services.
  2. Link existing chapters — do not copy their labs.
  3. Design for failure: retries, DLQ, idempotency, rollback.
  4. Measure before you buy provisioned concurrency or multi-region.

17. Architecture decision checklist

  1. Write the user journey in five bullets with no AWS names.
  2. Mark each step sync (user waits) or async.
  3. Name failure mode: retry, DLQ, compensate, or alert-only.
  4. Name the idempotency key for every write.
  5. Pick data store from access patterns (link DynamoDB modeling).
  6. Estimate monthly cost at 1x and 10x traffic (USD and INR).
  7. Confirm account concurrency and service quotas in ap-south-1.
  8. Decide auth: Cognito, IAM, Lambda authorizer, or none.
  9. Name on-call and which CloudWatch alarm pages them.
  10. Link the deep chapter you will not rewrite.
  11. Only then open console or IaC.

18. Copy-paste quick commands (read-only first)

# Region and identity
aws configure get region
aws sts get-caller-identity

# Lambda landscape
aws lambda list-functions --region ap-south-1 --max-items 20 \
  --query 'Functions[].{N:FunctionName,R:Runtime,T:Timeout,M:MemorySize}' --output table
aws lambda get-account-settings --region ap-south-1

# API Gateway (HTTP APIs)
aws apigatewayv2 get-apis --region ap-south-1 --query 'Items[].{N:Name,Id:ApiId,Ep:ProtocolType}' --output table

# Queues and topics
aws sqs list-queues --region ap-south-1
aws sns list-topics --region ap-south-1 --query 'Topics[].TopicArn'

# Event buses and state machines
aws events list-event-buses --region ap-south-1
aws stepfunctions list-state-machines --region ap-south-1 --query 'stateMachines[].name'

# DynamoDB tables (names only)
aws dynamodb list-tables --region ap-south-1

Run these in a sandbox account. Prefer read-only IAM while learning.

19. More industry and stack stories

  • Fintech (Aisha, Lagos, NGN): bank webhooks must return 200 fast — SQS absorbs spikes; ledger Lambda is idempotent on paymentId.
  • Ecommerce (Rohan, Pune, INR): Black Friday — API Gateway throttle + SQS order intake; SNS fans inventory, email, analytics.
  • Healthcare (Mei, Singapore, SGD): appointment reminders via SNS SMS; PHI only in DynamoDB with condition keys.
  • EdTech (Diego, São Paulo, BRL): EventBridge nightly cleanup of draft quizzes; Lambda timeout 30s, not 15 min.
  • Logistics (Fatima, Casablanca, MAD): package scans on custom EventBridge bus; Step Functions customs saga.
  • Media (Kenji, Osaka, JPY): S3 → Lambda thumbnails; never write thumbs to the watched prefix.
  • SaaS (Priya, Bengaluru, INR): Cognito groups + DynamoDB PK tenantId; one Lambda authorizer for all routes.
  • Gov (Omar, Amman, JOD): strangler — peel one PDF form route per sprint from the monolith.
  • Startup (Sofia, Sofia, EUR): start with Function URL for demos; move to HTTP API when partners need JWT.
  • Retail (Luis, Mexico City, MXN): store POS sync via SQS FIFO when order matters; Standard when it does not.
  • Python: handlers thin; put domain logic in plain modules for unit tests without Lambda.
  • Node: prefer async/await; never block the event loop on sync DNS.
  • Java: SnapStart for cold starts; keep dependencies lean.
  • .NET: AspNetCoreServer for low-traffic tenants; watch package size.
  • Go: single static binary; great for SQS workers.
  • PHP: keep Laravel queues on ECS; Lambda for S3/webhooks glue.

20. Glossary (short)

TermMeaning
Cold startFirst invoke pays init; later invokes reuse the env
IdempotencySame request twice → same effect
DLQDead-letter queue for failed messages
ChoreographyServices react to events; no central conductor
OrchestrationCentral workflow (Step Functions) directs steps
Fan-outOne event → many consumers
Fan-inMany branches join before next step
Strangler figPeel routes from monolith gradually
SagaDistributed tx via steps + compensations
Provisioned concurrencyKeep N envs warm; you pay for ready capacity

21. Practice: explain out loud

  1. 60 seconds: everyday story for strangler fig migration.
  2. 60 seconds: sync vs async with a checkout example.
  3. 60 seconds: when you refuse Lambda.
  4. 60 seconds: DLQ + idempotency in one breath.
  5. Record once; cut fillers; record again.

22. Safe lab hygiene

  • Tag every lab resource with owner and expiry date.
  • Set a monthly AWS Budget alarm in INR or USD before experiments.
  • Prefer read-only commands first; mutate in a sandbox account.
  • Delete queues, APIs, tables you created — DynamoDB and APIGW leave footprints.
  • Never put production secrets in env vars or screenshots.
  • Do not enable provisioned concurrency for a hello-world.

24. Myths to drop

MythReality
Serverless means zero serversServers exist; you do not manage them
Always cheaper than EC2Steady high load can favor EC2/Savings Plans
No Ops neededYou own IAM, data, alarms, cost, incidents
One Lambda per app is fineBounded contexts scale better
Queues are optional decorationQueues are the load leveler and blast-radius wall

25. Error budget thinking for serverless

If your monthly error budget is 0.1% on checkout, a fan-out that retries aggressively can burn the budget with duplicate emails while money stays correct. Separate business correctness SLOs from notification SLOs.

  1. Write two SLOs: money-correct and notify-delivered.
  2. Retries on money path: bounded + idempotent.
  3. Retries on notify path: best-effort + DLQ.
  4. Page humans on money DLQ; ticket on notify DLQ.

26. Regional notes (ap-south-1)

  • Build labs in Mumbai (ap-south-1) unless your org mandates elsewhere.
  • Some services launch first in us-east-1 — check feature availability.
  • Data residency for INR fintech may require in-region only.
  • Latency to end users in India usually favors ap-south-1.

27. Naming conventions that save incidents

# Suggested prefixes
# Lambda:  pay-intake-prod, pay-worker-prod
# SQS:     pay-orders.fifo / pay-orders-dlq
# SNS:     pay-order-events
# EB bus:  pay.domain
# SFN:     pay-refund-saga
# DDB:     pay-orders-prod

Include env (dev/stage/prod) and domain. Future you grepping CloudWatch will thank present you.

28. Pre-mortems (ten minutes)

  1. Imagine tomorrow headline: double charge in AED. What broke?
  2. Imagine DLQ depth 50,000 after a bad deploy. How do you drain?
  3. Imagine Cognito outage. Do APIs fail closed or serve read-only?
  4. Write answers in the runbook before go-live.

29. Currency and locale in examples

Rotate currencies in designs: INR, USD, EUR, AED, NGN, BRL, JPY, SGD. Rotate names: Aisha, Rohan, Mei, Diego, Fatima, Kenji, Priya, Omar, Sofia, Luis. This keeps mental models global — not one-country samples.

30. Worked story: Priya SaaS webhooks (INR)

  1. Monolith /v1/webhooks overloaded on Black Friday.
  2. Facade sends /v1/webhooks to Lambda+SQS.
  3. 1% canary one day; errors flat; 100% next day.
  4. Monolith handler deleted two weeks later after zero hits.

31. Anti-patterns

  • Rewriting the database and the API on day one.
  • No parity tests — silent field renames.
  • Peeling checkout before login health is green.

Revision, interview and comparison cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: Strangler not big-bang. Weekend rewrites of monoliths burn teams and customers. Route new slices to Lambda behind a facade; leave the rest on the monolith. Pick one capability → parity tests → route % traffic → keep rollback. Priya Deshmukh migrates read APIs first, writes later.
Revision card: Strangler not big-bang · Download PNG · Open card page
Revision card: Behavioral parity. Shipping a different response shape breaks every client silently. Compare status, body, and side effects old vs new before cutover. Shadow traffic → diff logs → then serve Lambda responses. Kenji Tanaka keeps a one-click route rollback for a week.
Revision card: Behavioral parity · Download PNG · Open card page
Comparison: Big-bang rewrite vs Strangler fig. Big-bang rewrite: Replace the monolith in one cutover. Strangler fig: Route slices gradually behind a facade.
Comparison: Big-bang rewrite vs Strangler fig · Download PNG · Open card page
Comparison: Client→Lambda direct vs Facade routing. Client→Lambda direct: Clients call new Function URL/API themselves. Facade routing: API Gateway/ALB keeps one contract, routes by path.
Comparison: Client→Lambda direct vs Facade routing · Download PNG · Open card page
Interview card: Slice by capability. Extracting random files without a capability boundary thrashs teams. Cut one user-facing capability with clear data ownership next. MNC: which slice would you take first from a retail monolith?
Interview card: Slice by capability · Download PNG · Open card page
Interview card: Facade at the edge. Clients calling monolith and Lambda URLs directly couple forever. API Gateway/ALB facade routes by path while clients stay stable. MNC: show a path rule that sends /orders/read to Lambda.
Interview card: Facade at the edge · Download PNG · Open card page
Interview card: Shadow before serve. Flipping 100% on day one hides behavioral diffs until outage. Mirror traffic to Lambda, compare, then ramp served percentage. MNC: what do you compare in shadow mode?
Interview card: Shadow before serve · Download PNG · Open card page
Interview card: Data ownership is hard. Two writers on one shared table recreate the monolith in the database. Plan ownership, dual-write, or CDC before cutting write paths. MNC: dual-write vs CDC for inventory — pick and defend.
Interview card: Data ownership is hard · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practice Tasks

About this scenario

London Legal LLP is a law business in London. Oliver Hughes looks after its IT and cloud work. They count money in GBP and run their AWS resources in the eu-west-2 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy Strangler wraps old — 1

Why: Idea.

What to do: Enter 1 if strangler fig routes new traffic around the old monolith gradually.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Facade at edge — 1

Why: Edge.

What to do: Enter 1 if a facade or API Gateway often sits in front during migration.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Slice by capability — 1

Why: Cut.

What to do: Enter 1 if you extract one capability at a time not the whole app.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Route by path — 1

Why: Traffic.

What to do: Enter 1 if path or host routing can send some URLs to Lambda.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Get REST APIs

Why: CLI.

What to do: List REST APIs

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Strangler YAML

Why: Map.

What to do: YAML: edge: apigw, old: monolith, new: lambda.

How:
  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Easy Compare error rates — 1

Why: Verify.

What to do: Enter 1 if you compare error and latency metrics old vs new during cutover.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Behavioral parity — 1

Why: Safe.

What to do: Enter 1 if new Lambda paths need behavioral parity tests vs monolith.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Dual write carefully — 1

Why: Data.

What to do: Enter 1 if dual-writes during cutover need careful consistency plans.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Keep rollback path — 1

Why: Ops.

What to do: Enter 1 if you keep a quick route rollback to the monolith.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Shadow traffic — 1

Why: Verify.

What to do: Enter 1 if shadowing traffic to Lambda without serving responses helps verify.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Cut plan YAML

Why: Plan.

What to do: YAML: first: read_path, later: write_path.

How:
  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Hard Data ownership last — 1

Why: Hard.

What to do: Enter 1 if shared database ownership is often the hardest cut.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Avoid big-bang cut — 1

Why: Anti.

What to do: Enter 1 if a single weekend big-bang rewrite is riskier than strangler.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Feature flags help — 1

Why: Control.

What to do: Enter 1 if feature flags help ramp Lambda traffic gradually.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Delete lab same day — 1

Why: Hygiene.

What to do: Enter 1 if lab-sph-strangle should be deleted same day.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.