Introduce Chaos Middleware for Python Flask: Simulate disruptions to improve resiliency
Tags: flask, resilience, chaos, devops
Published: 2020-09-28 05:44:24

**Resiliency** is key to software nowadays. It contributes to your application's reliability and plays a major role in the [competitive advantage of your business](https://medium.com/proofdock/how-chaos-engineering-increases-your-competitiveness-d83caa6ce2cb). Resilient applications smartly exploit the strengths of software patterns that handle timeouts, delays and faulty service responses.

Great authors and presenters like [Uwe Friedrichsen](https://www.slideshare.net/ufried/) and [Donald Firesmith](https://insights.sei.cmu.edu/author/donald-firesmith/) share their ideas and knowledge about **resilient software design**. Such articles describe software patterns that overcome disruptions and improve application resiliency in a handsome way.

However, deploying a resilience pattern requires you as a developer to **verify your implementation**. When touching the ground of verification, things appear to get difficult.

Chaos engineering tools advertise features like stopping a virtual machine, or to terminate pods in your Kubernetes cluster. The "blast radius" gets high here. Higher than a developer expects when exploring a resilience design pattern on Friday afternoon at 2PM.

That is where the ``Chaos Middleware`` package goes into action. The [Cloud Bug Study](https://ucare.cs.uchicago.edu/pdf/socc14-cbs.pdf) states, that neglected error handling - buggy code, timeouts, and others - leads to a great portion of a system's unavailability.

The ``Chaos Middleware`` allows you to throw your application at turbulent conditions. It lets you simulate delayed responses or raise errors. Activate disruptions when needed and narrow them down on specific URL paths. The ``Chaos Middleware`` gives you the opportunity to minimize the "blast radius" and verify your application's resilience, even on a Friday afternoon.

The next sections will guide you through _i)_ the installation and configuration process in your Flask application _ii)_ and the simulation of delays and application faults. Simulations are enabled by HTTP header requests or by the [``Chaos Platform``](https://docs.proofdock.io/chaos/guide/) control panel.

## Installation & configuration

1. Install the ``Chaos Middleware`` for the Flask application:
     ```bash
     cd /path/to/your/flask-application  # Enter your Flask application
     venv/bin/activate  # Active virtual environment
     pip install -U proofdock-chaos-middleware-flask
     ```

1. Configure the Flask application:
     ```python
     from flask import Flask, jsonify
     from pdchaos.middleware.contrib.flask.flask_middleware import FlaskMiddleware

     app = Flask(__name__)
     app.config['CHAOS_MIDDLEWARE_APPLICATION_NAME'] = 'example-application-name'
     app.config['CHAOS_MIDDLEWARE_APPLICATION_ENV'] = 'example-environment'
     app.config['CHAOS_MIDDLEWARE_PROOFDOCK_API_TOKEN'] = 'eyJ0eXAi...05'
     
     middleware = FlaskMiddleware(app)
     
     # Your business logic here

     @app.route("/products")
     def hello():
         return "Hello, from the products"

     if __name__ == "__main__":
         app.run()
     ```

1. Start your application

## Simulate delays

Trigger delays by setting the `x-proofdock-attack` request header. The `Chaos Middleware` detects any value inside this header. 

Set the header's value to `{"actions":[{"name":"delay","value":"15"}]}`. The value describes the simulation ``name`` and its ``value`` in seconds. The described simulation delays the response by 15 seconds.

For the simulation, we use the Postman client to visualize the HTTP requests.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/kdp143wjlxyd7fnqd1e1.gif)
*A delay simulation*

## Simulate faults

Raise exceptions by setting the `x-proofdock-attack` request header.

Set the header's value to `{"actions":[{"name":"fault","value":"Exception"}]}`. The value describes the simulation ``name`` and its ``value`` as a fully qualified name of the exception to be raised. The simulation will raise the `Exception`.

</br>
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/i76rumlxvwjg3rdi2e1c.gif)
*A fault simulation*

## A control panel for Azure DevOps users

A more appealing way to control such attacks is the usage of the control panel provided by Proofdock's [``Chaos Platform``](https://docs.proofdock.io/chaos/guide/). The ``Chaos Platform`` extends the Azure DevOps with chaos engineering capabilities. The control panel allows you to control application attacks via a graphical user interface and lets your application cache the configured attack. Check out the [**docs**](https://docs.proofdock.io/chaos/guide/) when you are interested in the ``Chaos Platform``.


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4xs9vhcsdtmqp83tffan.png)
*The control panel in Azure DevOps*


## Thank you

We hope you had fun and learned some new aspects on resilience.

We are [**Proofdock**](https://proofdock.io), a software tech company located in Germany helping engineers build more resilient and reliable software products. Check out the [**Chaos Platform**](https://marketplace.visualstudio.com/items?itemName=proofdock.chaos-platform) for Microsoft Azure and explore your system.

## References
- Check out the source code at [GitHub](https://github.com/proofdock/chaos-middleware-python/)
- [Read the docs](https://docs.proofdock.io/)
- Install the [``Chaos Platform``](https://marketplace.visualstudio.com/items?itemName=proofdock.chaos-platform)