DEV Community

Bùi Quang
Bùi Quang

Posted on

Building a High-Performance Async LRU Cache with TTL in Python

Building a High-Performance Async LRU Cache with TTL in Python

In modern asynchronous Python applications, in-memory caching is crucial for reducing database load and speeding up API responses. While standard dictionaries or functools.lru_cache work well for synchronous code, they lack native support for asynchronous lock safety and Time-To-Live (TTL) expiration.

In this article, we'll explore how to build a robust, thread-safe and async-safe LRU (Least Recently Used) cache with custom TTL support from scratch using Python's asyncio.

Core Features

  1. Async-Safe Locks: Using asyncio.Lock to prevent race conditions during concurrent reads and writes.
  2. TTL Expiration: Automatic purging of stale items upon retrieval or maintenance.
  3. LRU Eviction: Evicting the least recently used item when the maximum capacity is reached.

Implementation

Here is the clean implementation:

import time
import asyncio
from collections import OrderedDict
from typing import Any, Optional

class AsyncCacheEngine:
    def __init__(self, max_size: int = 1000):
        self.max_size = max_size
        self.cache: OrderedDict[str, tuple[Any, Optional[float]]] = OrderedDict()
        self.lock = asyncio.Lock()

    async def get(self, key: str) -> Optional[Any]:
        async with self.lock:
            if key not in self.cache:
                return None

            value, expires_at = self.cache[key]
            if expires_at is not None and time.time() > expires_at:
                del self.cache[key]
                return None

            self.cache.move_to_end(key)
            return value

    async def set(self, key: str, value: Any, ttl: Optional[float] = None) -> None:
        async with self.lock:
            expires_at = time.time() + ttl if ttl is not None else None
            if key in self.cache:
                self.cache.move_to_end(key)
            elif len(self.cache) >= self.max_size:
                self.cache.popitem(last=False)

            self.cache[key] = (value, expires_at)
Enter fullscreen mode Exit fullscreen mode

Conclusion

This lightweight async cache engine provides an efficient and reliable caching layer for your Python microservices and web apps. Feel free to check out our crypto wallets for support:

  • Base: 0x551a468628F6F35546E11dAcDa3d99EE75E61A8D

Top comments (0)