SkillSprout
Chapter 1 · Lesson 3
Intermediate
5 min read

Retries, Backoff and Throttling

Overview

Distributed systems fail in small, temporary ways: a dropped packet, a busy partition, a service rate limit. A robust client retries those failures, but doing so naively can make things worse by hammering a struggling service. The standard solution is exponential backoff with jitter.

Imagine a crowded doorway. If everyone who bumps into the door retries immediately, they collide again. If each person waits a little longer after every collision, and each picks a slightly random wait, the crowd spreads out and everyone gets through.

AWS SDKs implement retries for you, but you must understand the modes, which errors are retried and why your own operations must be idempotent to be safely repeated.

Key Concepts

  • Exponential backoff doubles the wait between retries (for example 100 ms, 200 ms, 400 ms) up to a cap.
  • Jitter adds randomness so many clients do not retry at the same instant (thundering herd).
  • SDK retry modes: legacy, standard (default in modern SDKs, 3 attempts) and adaptive (client-side rate limiting).
  • Retryable errors include throttling (ThrottlingException, ProvisionedThroughputExceededException, HTTP 429), 5xx and timeouts; 4xx validation errors are not retried.
  • DynamoDB SDKs use more retries (default 10 attempts in some SDKs) with a short base delay.
  • Retries require idempotent operations; use idempotency tokens or conditional writes.
  • Set sensible connect and read timeouts; an infinite wait is a failure mode.
  • Use a dead-letter queue after retries are exhausted to preserve the request.

Detailed Notes

Exponential backoff with full jitter

The AWS-recommended formula is: sleep = random(0, min(cap, base * 2^attempt)).

python
import random, time
from botocore.exceptions import ClientError

RETRYABLE = {"ThrottlingException", "ProvisionedThroughputExceededException",
             "RequestLimitExceeded", "ServiceUnavailable", "InternalError"}

def call_with_backoff(fn, max_attempts=6, base=0.1, cap=5.0):
    for attempt in range(max_attempts):
        try:
            return fn()
        except ClientError as e:
            code = e.response["Error"]["Code"]
            if code not in RETRYABLE or attempt == max_attempts - 1:
                raise
            time.sleep(random.uniform(0, min(cap, base * 2 ** attempt)))

Letting the SDK do it

python
import boto3
from botocore.config import Config

cfg = Config(
    retries={"max_attempts": 8, "mode": "adaptive"},
    connect_timeout=3,
    read_timeout=10,
)
ddb = boto3.client("dynamodb", config=cfg)
javascript
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
const ddb = new DynamoDBClient({ maxAttempts: 8, retryMode: "adaptive" });

The same can be set with AWS_RETRY_MODE and AWS_MAX_ATTEMPTS environment variables.

Retry modes

ModeBehaviour
legacyOlder default; service-specific retry counts
standardConsistent across SDKs; exponential backoff with jitter; retry quota
adaptiveStandard plus a client-side token bucket that slows requests when throttled (experimental)

Retry or not?

ErrorRetry?
ThrottlingException / 429Yes, with backoff
500, 502, 503, 504Yes
Connection reset, timeoutYes, if idempotent
ValidationException (400)No, fix the request
AccessDeniedException (403)No
ConditionalCheckFailedExceptionNo, it is a business signal

Idempotency

If a retry runs an operation twice, the result must be the same. Techniques:

  • Natural idempotence: PutItem with the same key overwrites with the same data.
  • Idempotency token parameters, such as ClientRequestToken on EC2 RunInstances or Step Functions execution names.
  • Conditional writes (attribute_not_exists(pk)) to prevent duplicates.
  • Lambda Powertools Idempotency utility, which stores results in DynamoDB.

Protecting downstream systems

Backoff alone is not enough if every client retries for a long time. Combine it with:

  • A retry budget or circuit breaker that stops calling a failing dependency.
  • Queues (SQS) so work waits rather than retries instantly.
  • Reserved capacity or on-demand tables for predictable throughput.

Failure inside Lambda

Asynchronous Lambda invocations are retried twice by default; configure maximum retry attempts (0-2), maximum event age and an on-failure destination or DLQ. SQS-triggered Lambda retries by returning the message to the queue after the visibility timeout.

Partial failures in batch APIs

Many APIs return success for the call while individual items fail. Ignoring those items silently drops data. Always inspect the response.

APIWhat to check
DynamoDB BatchWriteItem / BatchGetItemUnprocessedItems / UnprocessedKeys
Kinesis PutRecordsFailedRecordCount and per-record ErrorCode
SQS SendMessageBatchFailed list
EventBridge PutEventsFailedEntryCount
SNS PublishBatchFailed list
python
def batch_write(client, table, requests_, max_rounds=6):
    pending = {table: requests_}
    for attempt in range(max_rounds):
        resp = client.batch_write_item(RequestItems=pending)
        pending = resp.get("UnprocessedItems") or {}
        if not pending:
            return
        time.sleep(random.uniform(0, min(2.0, 0.05 * 2 ** attempt)))
    raise RuntimeError("items still unprocessed: %d" % len(pending[table]))

Timeouts and deadlines

Retries are bounded by a total time budget. In Lambda, read context.get_remaining_time_in_millis() and stop retrying when less than the next backoff plus a safety margin remains, so the function returns a clean error instead of timing out. Use short connect timeouts (1-3 s) and read timeouts sized to the 99th percentile of the dependency.

Client-side vs service-side limits

Throttling can be caused by account quotas, resource limits (per-partition throughput), or your own concurrency. Check Service Quotas and CloudWatch throttle metrics before assuming a code bug, and use quota-increase requests when the demand is legitimate.

Real World Example

A ticketing site wrote bookings to DynamoDB from many workers. During a sale the table throttled and workers retried instantly in a tight loop, which kept it throttled. After enabling the SDK's standard retry mode with jitter, adding a SQS buffer and using a conditional write to prevent double bookings, throttling dropped sharply and no customer was charged twice even when a retry occurred.

Architecture Diagram

Retry with exponential backoff
Architecture
Client
App + SDK
Throttled429
Retry w/ jitter
DLQ / alarm

Each failed attempt waits longer; exhausted requests go to a dead-letter queue.

  1. 1The first call is throttled and returns a retryable error.
  2. 2The SDK waits a random time up to a doubling cap.
  3. 3It retries until success or the attempt limit.
  4. 4On final failure the request is parked in a DLQ and an alarm fires.

Best Practices

  • ✓Use SDK standard or adaptive retry mode before writing custom loops.
  • ✓Always add jitter to backoff.
  • ✓Make operations idempotent before enabling retries.
  • ✓Set explicit timeouts and a maximum attempts count.
  • ✓Send exhausted requests to a DLQ and alarm on it.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • Throttling or ProvisionedThroughputExceededException -> exponential backoff (and increase capacity if persistent).
  • The answer to a thundering herd is jitter.
  • Retries need idempotency; look for tokens or conditional expressions.
  • Async Lambda failures: configure retries, destinations or DLQ.

Finished this lesson?

0 of 46 lessons done · 0% of the course