Async Debounce & Throttle Decorator
Fast user input can trigger dozens of redundant async queries per second. Debouncing delays execution until quiet time passes, while throttling limits calls to at most once per duration. Implementing these in asyncio requires managing task cancellation and timestamps.
import asyncio
def async_throttle(seconds: float):
def decorator(fn):
last_run = 0.0
async def wrapper(*args, **kwargs):
nonlocal last_run
now = asyncio.get_running_loop().time()
if now - last_run >= seconds:
last_run = now
return await fn(*args, **kwargs)
return wrapper
return decorator
# Async Debounce & Throttle Decorator When users hammer a search bar or an upstream broker floods events, triggering an async remote call on every single trigger melts your backend. 🏎️💨 **Debounce** discards earlier pending requests and waits for silence before firing. **Throttle** guarantees that no matter how many times a coroutine is called, it fires at most once every $N$ seconds, returning the latest result to caller storms without hammering I/O. ```python import asyncio def async_throttle(interval: float): def decorator(fn): last_called = 0.0 cached_result = None async def wrapper(*args, **kwargs): nonlocal last_called, cached_result now = asyncio.get_running_loop().time() if now - last_called >= interval: last_called = now cached_result = await fn(*args, **kwargs) return cached_result return wrapper return decorator ``` ## Pop Quiz What happens in an async debounce decorator when a second call arrives before the delay timer expires? - [ ] The active timer task is cancelled and rescheduled, resetting the countdown window. - [ ] Both coroutines run concurrently and race to update the return value in shared memory. - [ ] The Python event loop pauses entirely until the first coroutine yields control. - [ ] An UnhandledPromiseRejection exception crashes the parent thread. ## Real-World Challenge Write an `async_throttle(interval_seconds: float)` decorator. It must protect async functions so that rapid back-to-back invocations within the time window return the cached result of the most recent run without re-executing the decorated function. <details> <summary>Solution</summary> ```python import asyncio import functools def async_throttle(interval_seconds: float): def decorator(fn): last_called = 0.0 cached_result = None lock = asyncio.Lock() @functools.wraps(fn) async def wrapper(*args, **kwargs): nonlocal last_called, cached_result async with lock: loop = asyncio.get_running_loop() now = loop.time() if now - last_called >= interval_seconds or cached_result is None: last_called = now cached_result = await fn(*args, **kwargs) return cached_result return wrapper return decorator # Verification async def run_test(): call_count = 0 @async_throttle(0.05) async def fetch_stock_price(): nonlocal call_count call_count += 1 return 100 + call_count v1 = await fetch_stock_price() v2 = await fetch_stock_price() assert v1 == 101 and v2 == 101 assert call_count == 1 await asyncio.sleep(0.06) v3 = await fetch_stock_price() assert v3 == 102 assert call_count == 2 asyncio.run(run_test()) ``` </details>