Debug School

rakesh kumar
rakesh kumar

Posted on

How to handle Multiple Requests Concurrently using ASGI

Main Purposes of ASGI
What is a Web Framework?
Simple Web Framework Example
Types of Web Frameworks
WSGI vs ASGI
Recommended frameworks by requirement
Recommended learning order

Main Purposes of ASGI

Use this as your blog heading:

ASGI Explained: 5 Reasons Modern Python Applications Need It

  1. Handle Multiple Requests Concurrently

ASGI allows the application to process other requests while waiting for databases, APIs or files.

  1. Support Asynchronous Programming

It provides native support for Python’s async and await, making I/O-heavy applications more efficient.

  1. Enable Real-Time Communication

ASGI supports WebSockets for live chat, notifications, order tracking and collaborative applications.

  1. Manage Long-Lived Connections

It can maintain connections required for streaming, Server-Sent Events, live dashboards and continuous updates.

  1. Improve Scalability and Resource Usage

ASGI can manage many concurrent connections without requiring a separate thread or process for every waiting request.

What is a Web Framework?

A web framework is a collection of ready-made tools that helps developers build websites, web applications and APIs.

Without a framework, developers must manually write code for:

Receiving HTTP requests
Sending HTTP responses
URL routing
Authentication
Database connections
Input validation
Security
Error handling
Cookies and sessions
Enter fullscreen mode Exit fullscreen mode

A web framework provides these common features, allowing developers to focus on business requirements.

Simple real-life example

Imagine you want to build a house.

Without a framework, you must manufacture everything yourself:

Bricks
Doors
Windows
Electrical equipment
Plumbing equipment
Enter fullscreen mode Exit fullscreen mode

With a framework, these building materials are already available. You only need to arrange and customize them.

Similarly, Django, Flask and FastAPI provide the building blocks needed to create web applications.

Simple Web Framework Example

Without discussing database or authentication, a framework lets you create an endpoint easily:

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
async def hello():
    return {"message": "Hello, Ashwani"}
Enter fullscreen mode Exit fullscreen mode

When someone opens:

http://localhost:8000/hello
Enter fullscreen mode Exit fullscreen mode

The server returns:

{
  "message": "Hello, Ashwani"
}
Enter fullscreen mode Exit fullscreen mode

Here, FastAPI manages the HTTP request, routing and JSON response.

Types of Web Frameworks

  1. Full-Stack Framework

A full-stack framework provides almost everything required to build a complete application.

Common features include:

URL routing
Database ORM
Authentication
Admin panel
Form handling
HTML templates
Sessions and cookies
Security features
Enter fullscreen mode Exit fullscreen mode

Examples:

Django
Ruby on Rails
Laravel
Spring Boot
Best scenario
Enter fullscreen mode Exit fullscreen mode

Use a full-stack framework when building:

Admin portals
E-commerce applications
School management systems
Content-management systems
Complete business applications
Enter fullscreen mode Exit fullscreen mode

Example

Django provides a model, admin panel and authentication system:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(
        max_digits=10,
        decimal_places=2
    )
Enter fullscreen mode Exit fullscreen mode
  1. Microframework

A microframework provides only the basic web-development features.

Usually, it contains:

Routing
Request handling
Response handling
Enter fullscreen mode Exit fullscreen mode

You add database, validation and authentication libraries according to your requirements.

Examples:

Flask
Bottle
Sinatra
Best scenario
Enter fullscreen mode Exit fullscreen mode

Use it for:

Small applications
Prototypes
Simple APIs
Projects requiring complete architectural freedom
Enter fullscreen mode Exit fullscreen mode

Flask example

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/products")
def products():
    return jsonify([
        {"id": 1, "name": "Laptop"},
        {"id": 2, "name": "Phone"}
    ])
Enter fullscreen mode Exit fullscreen mode
  1. API-First Framework

An API-first framework is designed mainly for building APIs that return JSON to frontend or mobile applications.

Examples:

FastAPI
Django REST Framework
NestJS
Enter fullscreen mode Exit fullscreen mode

Common features include:

Request validation
JSON responses
API documentation
Authentication support
Serialization
Enter fullscreen mode Exit fullscreen mode

Best scenario

Use it for:

React application backends
Mobile application backends
Microservices
AI applications
Booking and payment APIs
Enter fullscreen mode Exit fullscreen mode

FastAPI example

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Product(BaseModel):
    name: str
    price: float

@app.post("/products")
async def create_product(product: Product):
    return {
        "message": "Product created",
        "product": product
    }
Enter fullscreen mode Exit fullscreen mode
  1. Asynchronous Framework

An asynchronous framework can serve other requests while waiting for slow I/O operations.

Examples:

FastAPI
Starlette
Sanic
Tornado
Enter fullscreen mode Exit fullscreen mode

It is useful when the application frequently waits for:

Database queries
External APIs
File operations
AI models
Network services
Enter fullscreen mode Exit fullscreen mode

Example

from fastapi import FastAPI
import asyncio

app = FastAPI()

@app.get("/payment-status")
async def payment_status():
    await asyncio.sleep(2)

    return {"status": "successful"}
Enter fullscreen mode Exit fullscreen mode

During the two-second wait, the server can process other requests.

WSGI vs ASGI

Full forms

WSGI: Web Server Gateway Interface
ASGI: Asynchronous Server Gateway Interface

Enter fullscreen mode Exit fullscreen mode

They define how a Python web server communicates with a Python web application.

User → Web Server → WSGI/ASGI → Python Application
Tabular difference

Simple real-world example
WSGI: One cashier per counter

Imagine one customer gives the cashier a task that takes five minutes.

The cashier waits until the task finishes before handling the next customer.

To serve more customers, the shop needs more cashiers.

ASGI: Restaurant waiter

A waiter takes your order and sends it to the kitchen.

While the kitchen prepares your food, the waiter serves other customers. When your food is ready, the waiter returns.

ASGI works similarly when waiting for:

Database results
Payment gateways
External APIs
AI-model responses
WSGI Coding Example

Flask commonly runs as a WSGI application.

from flask import Flask
import time

app = Flask(__name__)

@app.get("/order")
def create_order():
    # Blocking operation
    time.sleep(3)

    return {
        "message": "Order created"
    }

Enter fullscreen mode Exit fullscreen mode

Run it with Gunicorn:

gunicorn app:app --workers 4
Enter fullscreen mode Exit fullscreen mode

When time.sleep(3) executes, that worker remains blocked for three seconds.

The four-worker configuration allows multiple requests to be processed, but each waiting request occupies a worker.

ASGI Coding Example

FastAPI runs as an ASGI application.

from fastapi import FastAPI
import asyncio

app = FastAPI()

@app.get("/order")
async def create_order():
    # Non-blocking waiting operation
    await asyncio.sleep(3)

    return {
        "message": "Order created"
    }
Enter fullscreen mode Exit fullscreen mode

Run it with Uvicorn:

uvicorn app:app --host 0.0.0.0 --port 8000
Enter fullscreen mode Exit fullscreen mode

While one request is waiting, the event loop can process other requests.

Important difference in the code

WSGI-style blocking code:

time.sleep(3)

ASGI-style non-blocking code:

await asyncio.sleep(3)

It is not enough to write async def. The database client and external API libraries must also support asynchronous operations.

Database Example
Synchronous WSGI-style operation

@app.get("/orders")
def get_orders():
    orders = sync_database.query("SELECT * FROM orders")
    return {"orders": orders}

The worker waits until the database responds.

Asynchronous ASGI-style operation
@app.get("/orders")
async def get_orders():
    orders = await async_database.fetch(
        "SELECT * FROM orders"
    )

    return {"orders": orders}
Enter fullscreen mode Exit fullscreen mode

FastAPI can handle other requests while the database operation is waiting.

Recommended frameworks by requirement

Recommended learning order

FastAPI — make this your primary Python

Top comments (0)