DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Building Scalable Data Lake Using AWS
  • Building a Scalable ML Pipeline and API in AWS
  • AWS Step Functions Local: Mocking Services, HTTP Endpoints Limitations
  • From Zero to Scale With AWS Serverless

Trending

  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • AI, ML, and Data Science: Shaping the Future of Automation
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Breaking AWS Lambda: Chaos Engineering for Serverless Devs

Breaking AWS Lambda: Chaos Engineering for Serverless Devs

Our serverless system crashed from traffic surges. With chaos engineering, we purposely broke Lambda, tested failures with AWS FIS, and achieved 99% uptime, 30s MTTR!

By 
Bharath Kumar Reddy Janumpally user avatar
Bharath Kumar Reddy Janumpally
·
Mar. 24, 25 · Analysis
Likes (2)
Comment
Save
Tweet
Share
4.3K Views

Join the DZone community and get the full member experience.

Join For Free

The Day Our Serverless Dream Turned into a Nightmare

It was 3 PM on a Tuesday. Our "serverless" order processing system — built on AWS Lambda and API Gateway — was humming along, handling 1,000 transactions/minute. Then, disaster struck. A sudden spike in traffic caused Lambda timeouts, API Gateway threw 5xx errors, and customers started tweeting, “Why can’t I check out?!”

The post-mortem revealed the harsh truth: we’d never tested failure scenarios. Our “resilient” serverless setup had no fallbacks, retries, or plans for chaos.

That’s when I discovered chaos engineering — the art of intentionally breaking things to build unbreakable systems. In this guide, I’ll show you how to use AWS Fault Injection Simulator (FIS) to sabotage your Lambda functions, handle failures gracefully, and sleep soundly knowing your system can survive anything.

Chaos Engineering 101: Why Break What Isn’t Broken?

Chaos engineering is like a fire drill for your code. Instead of waiting for disasters, you proactively simulate failures to:

  1. Uncover hidden weaknesses (e.g., Lambda timeouts, cold starts).
  2. Validate recovery strategies (retries, fallbacks, circuit breakers).
  3. Build team confidence (because “tested” beats “hoped”).

Serverless chaos challenges:

  1. No servers to kill, but Lambda can throttle, timeout, or crash.
  2. Dependencies (DynamoDB, SQS) can fail silently.
  3. Stateless functions require new failure modes.

Step 1: Simulating Lambda Chaos With AWS FIS

AWS Fault Injection Simulator (FIS) is your chaos playground. While FIS doesn’t natively support Lambda yet, we can hack it using IAM policies and resource tagging.

Example: Simulating Lambda Throttling

Goal

Force Lambda to return TooManyRequestsException.

Step 1

Tag your Lambda function for targeting:

Plain Text
 
aws lambda tag-resource --resource arn:aws:lambda:us-east-1:123456789:function:OrderProcessor\


Step 1


Step 2

Create an IAM policy that denies lambda:InvokeFunction:

Step 2


Step 3

Attach the policy to a role/user during the experiment.

Result

API Gateway calls to this Lambda will fail with 403 Forbidden, mimicking throttling.

Step 2: Handling Retries and Timeouts

Lambda Configuration

1. Set Timeouts

Always lower than API Gateway’s timeout (29 seconds max). // AWS SDK v2: 

Java
 
//Set timeout to 10 seconds
LambdaClient lambdaClient = LambdaClient.builder()
  .overrideConfiguration(ClientOverrideConfiguration.builder()
    .apiCallTimeout(Duration.ofSeconds(10))
    .build())
  .build();


2. Retry Strategies

Use exponential backoff.

Java
 
RetryPolicy retryPolicy = RetryPolicy.builder()
  .numRetries(3)
  .backoffStrategy(BackoffStrategy.defaultExponentialDelay())
  .build();


3. API Gateway Fallbacks

Configure a Mock Integration as a fallback when Lambda fails:

YAML
 
x-amazon-apigateway-integration:
  uri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789:function:FallbackHandler/invocations
  responses:
    default:
      statusCode: "200"
  passthroughBehavior: when_no_templates
  requestTemplates:
    application/json: '{"statusCode": 200}'
timeoutInMillis: 5000


Fallback response:

JSON
 
{
  "status": "Service unavailable. Try again later."
}


Step 3: Building a Self-Healing Lambda Function (Java Example)

The Sabotage Function

A Lambda that fails randomly to simulate instability:

Java
 
public class ChaosLambdaHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

  private final Random random = new Random();

  @Override
  public APIGatewayProxyResponseEvent handleRequest(
    APIGatewayProxyRequestEvent input, Context context
  ) {
    // Fail 30% of the time
    if (random.nextDouble() < 0.3) {
      throw new RuntimeException("Chaos induced failure!");
    }

    return new APIGatewayProxyResponseEvent()
      .withStatusCode(200)
      .withBody("{\"status\": \"Success\"}");
  }
}


The Recovery Strategy

1. Retry with backoff:

Java
 
public APIGatewayProxyResponseEvent handleRequest(
  APIGatewayProxyRequestEvent input, Context context
) {
  int retries = 0;
  while (retries < 3) {
    try {
      return processOrder(input);
    } catch (RuntimeException e) {
      retries++;
      Thread.sleep((long) Math.pow(2, retries) * 100); // Exponential backoff
    }
  }
  throw new RuntimeException("All retries failed");
}


2. Fallback to SQS queue:

Java
 
private void sendToDeadLetterQueue(String message) {
  SqsClient sqsClient = SqsClient.create();
  SendMessageRequest request = SendMessageRequest.builder()
    .queueUrl("https://sqs.us-east-1.amazonaws.com/123456789/OrderDeadLetterQueue")
    .messageBody(message)
    .build();
  sqsClient.sendMessage(request);
}


Case Study: Breaking an Order Processor on Purpose

Scenario

A serverless order API processing $10k/hour.

Chaos Experiment

  1. Inject throttling: Using AWS FIS, deny Lambda invocations for 5 minutes.
  2. Simulate timeouts: Configure Lambda timeout to 1 second (too short for processing).

Observed Failures

  • 40% of requests failed with 503 Service Unavailable.
  • Retries overwhelmed the system, causing cascading failures.

Fixes Implemented

  1. Circuit breaker: Stop retrying after three failures.
  2. Fallback to cached data: Serve stale order statuses from DynamoDB during outages.
  3. Load shedding: Reject non-critical requests (e.g., analytics) during high load.

Outcome

  • 99% of requests succeeded even during chaos experiments.
  • Mean time to recovery (MTTR) dropped from 15 minutes to 30 seconds.

FAQ: Chaos Engineering for Serverless Newbies

Q: Is chaos engineering safe for production?

  • A: Start in staging! Use AWS FIS tags to limit the blast radius.

Q: How do I monitor chaos experiments?

  • A: CloudWatch Alerts + X-Ray traces. Track:
    • ThrottledRequests (Lambda)
    • 5xxErrorRate (API Gateway)
    • ApproximateAgeOfOldestMessage (SQS dead-letter queues)

Q: What’s the biggest serverless chaos risk?

  • A: Overloading downstream services (e.g., DynamoDB). Always test dependencies.

Golden Rules of Serverless Chaos

  1. Start small. Break one thing at a time (e.g., single Lambda).
  2. Automate recovery. Retries, fallbacks, and circuit breakers are mandatory.
  3. Learn and iterate. Every failure is a lesson.

Conclusion: Embrace the Chaos

Chaos engineering isn’t about breaking things for fun — it’s about knowing your system won’t break when it matters. By stress-testing your Lambda functions, designing for failure, and embracing tools like AWS FIS, you’ll build serverless apps that survive real-world storms.

Now, go break something — on purpose.

AWS AWS Lambda Chaos engineering

Opinions expressed by DZone contributors are their own.

Related

  • Building Scalable Data Lake Using AWS
  • Building a Scalable ML Pipeline and API in AWS
  • AWS Step Functions Local: Mocking Services, HTTP Endpoints Limitations
  • From Zero to Scale With AWS Serverless

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!