Reference library

Concurrency & performance

asyncio, threading, multiprocessing, and profiling-friendly performance patterns.

2 matches
Concurrency & performance medium

How to Implement a Token Bucket Rate Limiter with asyncio in Python

This code implements a thread-safe token bucket rate limiter for asyncio, allowing you to limit the rate of async tasks or API calls.

asyncio rate-limiting token-bucket
Python
import asyncio
import time


class TokenBucket:
    def __init__(self, rate_per_second, capacity):
        self.rate = rate_per_second
        self.capacity = capacity
        self.tokens = capacity
        self.last_refill = time.monotonic()
        self.lock = asyncio.Lock()

    async def acquire(self):
        asy…
14 0 Open
Concurrency & performance medium

Limit Concurrency with asyncio.Semaphore in Python

Use asyncio.Semaphore to cap how many async tasks run at once, throttling a batch of coroutines to a set concurrency limit.

asyncio concurrency semaphore
Python
import asyncio
import random


async def fetch_data(i: int, semaphore: asyncio.Semaphore) -> str:
    async with semaphore:
        print(f"Task {i} starts")
        await asyncio.sleep(random.uniform(0.1, 0.5))
        print(f"Task {i} finishes")
        return f"Result {i}"


async def main() -> None:
    semaphore …
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Concurrency & performance — Python code examples

What you will find here

This page collects concurrency & performance snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.