SkillSprout
Chapter 5 · Lesson 2
Advanced
5 min read

Resilient Third-Party Integrations and Circuit Breakers

Overview

Your application will depend on APIs you do not control: payment gateways, email providers, partner REST services. They will be slow or down at some point. A resilient integration limits the damage by timing out quickly, retrying only what is safe, stopping calls to a failing dependency and degrading gracefully.

A circuit breaker works like the electrical breaker in your home. When too many calls fail it trips to open, rejecting calls instantly instead of piling up waiting threads. After a cool-down it goes half-open, lets a trial request through and closes again if that succeeds.

On AWS you assemble these ideas from SDK retry settings, timeouts, SQS buffering with DLQs, Step Functions retry/catch, and small amounts of state in DynamoDB or ElastiCache to remember breaker status across Lambda environments.

Key Concepts

  • Timeouts are the first defence: a call without a timeout can hold a Lambda until its limit and cost money.
  • Retries need exponential backoff with jitter and a maximum attempt count to avoid retry storms.
  • Circuit breaker states: closed (normal), open (fail fast), half-open (probe).
  • Bulkhead isolation limits concurrency per dependency (reserved concurrency, separate queues).
  • Fallbacks return cached, default or partial data when a dependency fails.
  • DLQs and redrive keep failed messages for later inspection and replay.
  • Idempotency keys make retried POST requests safe with third parties.
  • Rate limiting protects partners; throttle with SQS and Lambda max concurrency.

Detailed Notes

Failure modes to design for

FailureSymptomMitigation
Dependency slowLambda timeouts, thread exhaustionShort timeout, circuit breaker
Dependency down5xx or connection errorsRetry with backoff, then open circuit and fall back
Partner rate limits youHTTP 429Queue and throttle, honour Retry-After
Duplicate requestDouble chargeIdempotency key
Poison messageMessage fails repeatedlyDLQ after maxReceiveCount

Retry with exponential backoff and jitter

python
import random, time, requests

def call_partner(payload, attempts=4):
    for n in range(attempts):
        try:
            r = requests.post(URL, json=payload, timeout=(2, 5),
                              headers={"Idempotency-Key": payload["id"]})
            if r.status_code < 500 and r.status_code != 429:
                return r
        except (requests.ConnectionError, requests.Timeout):
            pass
        time.sleep(random.uniform(0, min(8, 0.2 * 2 ** n)))   # full jitter
    raise RuntimeError("partner unavailable")

Never retry 4xx errors other than 429 and 408; they will not succeed.

A simple circuit breaker backed by DynamoDB

Lambda environments are short-lived and many run in parallel, so keep breaker state in a shared store.

python
import time, boto3
t = boto3.resource("dynamodb").Table("breaker")

def is_open(name):
    item = t.get_item(Key={"pk": name}).get("Item")
    return bool(item and item["openUntil"] > time.time())

def record_failure(name, threshold=5, cooldown=30):
    r = t.update_item(Key={"pk": name},
        UpdateExpression="ADD failures :one",
        ExpressionAttributeValues={":one": 1}, ReturnValues="UPDATED_NEW")
    if r["Attributes"]["failures"] >= threshold:
        t.update_item(Key={"pk": name},
            UpdateExpression="SET openUntil = :u, failures = :z",
            ExpressionAttributeValues={":u": int(time.time()) + cooldown, ":z": 0})

For a managed alternative, Step Functions state machines combine Retry (with BackoffRate and JitterStrategy) and Catch to route failures to a fallback state.

json
"CallPartner": {
  "Type": "Task",
  "Resource": "arn:aws:states:::lambda:invoke",
  "Retry": [{"ErrorEquals": ["States.TaskFailed"], "IntervalSeconds": 2,
             "MaxAttempts": 3, "BackoffRate": 2.0, "JitterStrategy": "FULL"}],
  "Catch": [{"ErrorEquals": ["States.ALL"], "Next": "UseCachedAnswer"}],
  "End": true
}

Buffering and throttling with SQS

Put outbound calls behind an SQS queue and cap the consumer with Lambda maximum concurrency on the event source mapping. The queue absorbs bursts, the cap respects the partner's rate limit, and a DLQ stores messages that exhaust maxReceiveCount. Set the queue visibility timeout to at least six times the function timeout.

Webhooks from third parties

Inbound webhooks should be acknowledged fast: validate the signature, write the payload to SQS or EventBridge and return 200 within a few seconds. Process later, because partners retry aggressively when you are slow, producing duplicates.

Graceful degradation

Decide ahead of time what the user sees when a dependency fails: cached recommendations, a "try again later" banner, or a queued confirmation email. Emit a metric when a fallback is used so you can alarm on it.

Real World Example

A ticketing company called a seat-map vendor synchronously during checkout. When the vendor degraded, every Lambda waited the full 30-second timeout and the whole site slowed. They set a 2-second timeout, added a DynamoDB-backed circuit breaker (5 failures opens for 30 seconds) and a fallback to a cached seat map. Checkout stayed responsive during the next vendor outage, and a CloudWatch alarm on the fallback metric alerted the on-call engineer.

Architecture Diagram

Circuit breaker in front of a partner API
Architecture
Integration
Callertimeouts + retries
Breaker stateopen / closed
Partner APIthird party
DLQ / retry queue

State in DynamoDB lets all Lambda environments share one view of the dependency.

  1. 1The caller reads the breaker state before calling the partner.
  2. 2If open, it returns a fallback immediately.
  3. 3If closed, it calls with a short timeout and bounded retries.
  4. 4Repeated failures trip the breaker and failed work goes to a queue or DLQ.

Best Practices

  • ✓Always set connect and read timeouts on outbound calls.
  • ✓Retry with exponential backoff and jitter and cap attempts.
  • ✓Use idempotency keys with third-party POST requests.
  • ✓Buffer outbound work in SQS, throttle with maximum concurrency, and attach a DLQ.
  • ✓Alarm on fallback and breaker-open metrics, not only on errors.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • Retry only on throttling, timeouts and 5xx; never on validation errors.
  • A DLQ captures messages that fail after maxReceiveCount; destinations capture failed async Lambda events.
  • Step Functions Retry/Catch is the managed way to add backoff and fallbacks.
  • Queue visibility timeout should be at least 6x the consuming function timeout.

Finished this lesson?

0 of 46 lessons done · 0% of the course