Snippets

A stash of small, reusable code snippets I reach for often.

Redis distributed lock (acquire)

Atomically acquire a lock with a unique token and an auto-expiry to avoid deadlocks.

bash
# NX = set only if absent, PX = expiry in ms
SET lock:order:42 "$RANDOM_TOKEN" NX PX 30000

Redis safe unlock (Lua, compare-and-delete)

Only release the lock if we still own it — prevents deleting someone else’s lock.

lua
if redis.call("get", KEYS[1]) == ARGV[1] then
  return redis.call("del", KEYS[1])
else
  return 0
end

Cron expression cheatsheet

The five fields are: minute hour day-of-month month day-of-week.

text
*   *   *   *   *    every minute
0   *   *   *   *    every hour
0   0   *   *   *    every day at 00:00
0   9   *   *   1-5  weekdays at 09:00
0   0   1   *   *    first day of every month

COUNT(*) vs COUNT(1)

They are identical to the optimizer. Prefer COUNT(*) — it is the standard idiom.

sql
-- same plan, same performance
SELECT COUNT(*) FROM orders WHERE status = 'paid';

Idempotent upsert (PostgreSQL)

Insert or update on conflict — safe to retry without creating duplicates.

sql
INSERT INTO accounts (id, balance)
VALUES ($1, $2)
ON CONFLICT (id) DO UPDATE
  SET balance = EXCLUDED.balance;

Graceful shutdown (Spring Boot)

Let in-flight requests finish before the process exits.

properties
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=30s