Created
November 7, 2025 23:50
-
-
Save shivamka1/c42d9a2fc0d1665022f4fd3277c24be7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function acquire_distributed_lock(key, ttl_ms) -> (ok, token): | |
| # e.g. SET key token NX PX ttl_ms in Redis | |
| ... | |
| function release_distributed_lock(key, token): | |
| # delete key only if stored token matches | |
| ... | |
| function purchase(productId): | |
| (ok, token) = acquire_distributed_lock("lock:product:" + productId, ttl_ms=5000) | |
| if not ok: | |
| return "Busy, try again" | |
| try: | |
| stock = query("SELECT stock FROM products WHERE id = ?", productId) | |
| if stock <= 0: | |
| return "Out of stock" | |
| exec("UPDATE products SET stock = stock - 1 WHERE id = ?", productId) | |
| return "OK" | |
| finally: | |
| release_distributed_lock("lock:product:" + productId, token) |
Comments are disabled for this gist.