tezvyn:

Mangum: Run Python ASGI Apps on Serverless

AI-drafted, machine-checkedSource: mangum.ioadvanced
Mangum: Run Python ASGI Apps on Serverless

Mangum is an adapter for running Python ASGI apps (like FastAPI) on serverless platforms like AWS Lambda. It translates serverless events into ASGI requests, letting you deploy existing async web apps without a rewrite.

WHY IT EXISTS: Modern Python web frameworks like FastAPI are built on the ASGI specification, designed for async servers. Serverless platforms like AWS Lambda have their own event-driven model. A bridge is needed to connect these two different worlds without rewriting the application to fit a platform-specific handler.

THE MENTAL MODEL: Think of Mangum as a universal adapter for your ASGI application. Your app is a device with a standard ASGI plug. A traditional server like Uvicorn is a standard ASGI wall socket. A serverless platform like AWS Lambda is a completely different type of socket. Mangum is the travel adapter that lets you plug your ASGI device into the Lambda socket, translating the event payloads so your application works without modification.

HOW IT WORKS: When a serverless function is invoked by an event, like an API Gateway request, the platform passes an event payload to the handler. Mangum takes this payload, which contains all the HTTP request details, and transforms it into the standard ASGI 'scope' dictionary. It passes this scope to your ASGI application. Your app processes the request and returns an ASGI response, which Mangum then translates back into the format required by the serverless platform to send back to the client.

WHEN TO USE IT: Use Mangum when you want to deploy an ASGI-compliant application (built with FastAPI, Starlette, etc.) to a serverless environment like AWS Lambda. It's perfect for building microservices or APIs where you want the benefits of serverless (auto-scaling, pay-per-use) without giving up the development experience of modern Python web frameworks.

WHEN NOT TO USE IT: Avoid Mangum if your application relies heavily on features that are at odds with the serverless execution model. This includes long-lived WebSocket connections, in-memory state that must persist between requests, or background tasks that exceed the function's maximum execution time. A traditional server is a better fit for these use cases.

ONE CANONICAL EXAMPLE: A developer builds a REST API using FastAPI. Instead of provisioning a server, they wrap the FastAPI application object with Mangum and deploy it as an AWS Lambda function fronted by an API Gateway. Each API call invokes the Lambda, Mangum translates the request, FastAPI processes it, and the response is returned, scaling automatically without server management.

Read the original → mangum.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.