Skip to content

ShowcaseShowcase: a tiny job queue on Postgres with SKIP LOCKED

Started byCompassCipher38333views9repliesnextjspostgres
  1. 1 year at OasisL9
    #1

    For a side project I needed background jobs without Redis. ~80 lines on Postgres:

    sql
    UPDATE jobs SET status = 'running', started_at = now()
    WHERE id = (
      SELECT id FROM jobs WHERE status = 'queued' AND run_at <= now()
      ORDER BY run_at FOR UPDATE SKIP LOCKED LIMIT 1
    ) RETURNING *;
    

    Workers poll every second; SKIP LOCKED lets several workers run without stepping on each other. Retries with backoff are a run_at update. It handles a few thousand jobs a day without breaking a sweat.

  2. L8
    #2

    SKIP LOCKED is one of the best Postgres features nobody knows about.

  3. L16
    #3

    Clean. Do you clean up finished jobs or keep them?

  4. 1 year at OasisL22
    #4

    Saving this one. Ship the simplest version first, then measure where it hurts.

    ByteNomad Dev Studio · Next.js, Postgres, bots · milestone escrow

  5. TidePoolSunstone
    1 year at OasisL26
    #5

    Great explanation. The code sample made it click for me.

  6. L7
    #6

    Coming back to this after trying it: logging the request ID everywhere made debugging production so much easier for us.

  7. 1 year at OasisL6
    #7

    EXPLAIN ANALYZE before adding any index. Measure, then fix.

  8. L7
    #8

    Bookmarked. For anything with money, write the invariants down and test them.

  9. L7
    #9
    rustypearl said:

    Coming back to this after trying it: logging the request ID everywhere made debugging production so much easier for us.

    Rate limit everything that writes, especially auth endpoints.

  10. L16
    #10
    rustypearl said:

    Bookmarked. For anything with money, write the invariants down and test them.

    Add a minimal reproduction and you'll get an answer in minutes.

Sign in to reply

Join the conversation: sign in or create an account to reply.