Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Welcome to the Chapter 2 Capstone Project! In modern microservices and backend web engineering, decorators provide non-invasive resilience, security, and performance optimizations.
In this project, you will build a production-grade UPI Banking Resilience Decorator Suite incorporating three industry-standard patterns:
def decorator_factory(param): def decorator(func): def wrapper(...)).@retry_on_failure): Automatically retries transient network or database errors with exponential backoff.@memoize): Eliminates redundant compute and database queries by caching return values in memory.@rate_limit): Protects sensitive financial APIs against high-frequency abuse.Imagine the payment processing pipeline powering Indian UPI transactions (PhonePe, Google Pay, Paytm):
+-------------------------------------------------------------------------+ | UPI PAYMENT GATEWAY RESILIENCE SHIELD | +-------------------------------------------------------------------------+ | | | Incoming Customer Payment: UPI ₹500 via HDFC Bank | | │ | | ▼ | | 1. @rate_limit(max_per_sec=3) ──> Blocks automated bots & spamming | | │ (Allowed) | | ▼ | | 2. @memoize_cache ──> Instantly returns cached bank IFSC & | | branch coordinates without DB hit | | │ (Not cached yet) | | ▼ | | 3. @retry_on_failure(3) ──> If cellular tower drops packet, | | silently retries bank switch 3 times | | │ (Success!) | | ▼ | | Core Banking Service: process_payment() Executes Successfully! | | | +-------------------------------------------------------------------------+
By wrapping our core payment function with these modular decorators, the business logic remains clean, readable, and 100% focused on financial accounting, while the decorators handle reliability and defense.
When a decorator needs configuration parameters (e.g. @retry(max_attempts=3)), it requires three levels of nested functions:
+-------------------------------------------------------------------------+ | THREE-TIER PARAMETERIZED DECORATOR PATTERN | +-------------------------------------------------------------------------+ | | | def retry(max_attempts=3): <-- 1. Decorator Factory (takes cfg)| | def actual_decorator(func): <-- 2. Decorator (takes function) | | @wraps(func) | | def wrapper(*args, **kwargs):<-- 3. Wrapper Closure (at call) | | # Execution logic using max_attempts and func | | return func(*args, **kwargs) | | return wrapper | | return actual_decorator | | | +-------------------------------------------------------------------------+
Here is the complete, modular, runnable code for the Decorator Suite:
| Practice | Bad Implementation | Gold-Standard Implementation |
|---|---|---|
| Parameterized Decorators | Trying to pass arguments to a 2-tier decorator | Use 3-tier pattern: Factory $\to$ Decorator $\to$ Wrapper |
| Retry Interception | Catching all exceptions (except:) blindly | Catch only transient network errors (allowed_exceptions=(...)) |
| Cache Keys | Using unhashable objects as cache keys | Normalize arguments to tuples or immutable representations |
| Cache Growth | Allowing unbounded cache memory growth | Use LRU (Least Recently Used) cache or bounded dictionary size |
| Rate Limiting | Static counters that never reset | Sliding-window timestamp pruning with time.time() |
def factory(config): def dec(func): def wrapper(*args, **kw): ...cache[args] = func(*args) avoids expensive re-computation of pure functions.@retry_on_failure turns fragile network calls into fault-tolerant distributed operations.@rate_limiter uses timestamp filtering to prevent denial-of-service and brute-force attacks.Build a logging decorator @log_to_file(filepath="app_audit.log") that:
filepath argument (defaulting to "app_audit.log").args and kwargs).with open(filepath, "a") context manager.@wraps.In the next lesson, we will continue your intermediate Python journey with Creating and Importing Modules (3: Modules and Packages).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Decorators Basics | Creating and Importing Modules |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.