Skip to content

Instantly share code, notes, and snippets.

@shivamka1
Created November 7, 2025 23:50
Show Gist options
  • Select an option

  • Save shivamka1/c42d9a2fc0d1665022f4fd3277c24be7 to your computer and use it in GitHub Desktop.

Select an option

Save shivamka1/c42d9a2fc0d1665022f4fd3277c24be7 to your computer and use it in GitHub Desktop.
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.