Correlation IDs and docker image

In Part 4 of this series, we implemented CRUD APIs. Now, we will cover the below features as a part of this post.

  • Adding Correlation ID with every request.
  • Build a docker image for this application.

The Part 5 implementation is available in the GitHub repository.

What are Correlation IDs?

A distributed system follows the microservices architecture pattern where the request goes through multiple microservices. It becomes difficult to track the end-to-end flow where various components are involved. If you get any issues reported by customers, it’s a nightmare to track if you don’t have the correct system in place. Correlation ID solves this problem.

A Correlation ID is a unique identifier that gets added during the first API interaction. The same identifier is propagated to the other microservices for the same request. You can draw a clear picture of the specific request using a logger and other systems.

Let's implement Correlation ID in the FastAPI

contextvars module: This module provides APIs to manage, store, and access context-local states.

pipenv install contextvars

We create an API interceptor class and add the logic to insert the Correlation ID with every API request if it is not in present the header.

Add this interceptor class to the FastAPI app defined in the main.py

app.add_middleware(RequestContextLogMiddleware)

You can call get_correlation_id() mentioned in the request_middleware.py to get the identifier and add it to subsequent logs.

Let’s run the application using the command

uvicorn app.main:app --env-file dev.env

Please ensure to run the Postgres docker container by applying the steps mentioned in the previous article.

Try executing /users API. The response will have an additional header Correlation-Id.

Build a docker image

In the real world, we always build a docker image for deployment purposes. We create a Dockerfile and take the base image as a slim-buster. This is lightweight and has worked well for us.

Let's build the image using the below command

docker build -f Dockerfile -t fastapi-app .

Output

REPOSITORY      TAG                   IMAGE ID       CREATED              SIZE
fastapi-app latest db1606fb0b3d About a minute ago 301MB

Now we add the fast-api-app service in the docker-compose file where we provide the environment variables too.

Open the swagger using the URL http://127.0.0.1:8000/docs.

Done !!!

Summary

If you follow all five articles in this series, you will understand how to build a production-grade application using FastAPI.

The whole project is available in the GitHub repository.

A quick link to articles from this series:

If this article is helpful, follow me to see my next articles.

--

--

Mohit

Founder @Stealth | Prev @Co-Founder @getphyllo.com