System Design

E8

Job queue with leases

The data structure is one ordered list and a mutex. The test is that no job goes to two workers while a lease is live, and that a dead worker does not lose a job.

Not startedSaved in this browser only.
  1. 1A lease is a claim with an end time. A dead worker frees its job by doing nothing.
  2. 2Each claim gets a new token. A worker that lost a lease gets 409 on every later call.
  3. 3Claim counts the attempt, so a job that kills its workers still stops.
  4. 4Production swaps one interface. SKIP LOCKED lets parallel claims take different rows.
E8
    A

    The spec

    as the interviewer states it
    Build a job queue as an HTTP service, in memory. Clients enqueue jobs with a priority. Workers claim the next job and hold it under a lease. A worker can extend its lease, complete the job, or fail it so that it retries. If a worker dies, its job returns to the queue when the lease expires. Many workers call the service at once, so make it safe.
    askanswer assumed
    What order?Highest priority first, 0 to 9. Equal priorities go by arrival.
    Who picks the lease length?The worker, in each claim. From 1 ms to 1 hour.
    How many attempts?3 by default, up to 10. An expired lease uses one.
    After the last attempt?The job is failed. No worker gets it again.
    Where does a retry go?Behind jobs of its own priority, with no delay.
    More than one queue?Yes, by name in the path. Names reach 64 bytes.

    Before I type, I confirm that a job can run twice after a crash, and that the worker must accept that.

    B

    The endpoints

    the contract the grader checks
    requestsuccesserrors
    POST /queues/{queue}/jobs201 job400
    POST /queues/{queue}/claim200 job, 204 empty400
    GET /jobs/{id}200 job404
    POST /jobs/{id}/heartbeat200 job400, 404, 409
    POST /jobs/{id}/complete200 job400, 404, 409
    POST /jobs/{id}/fail200 job400, 404, 409
    • Enqueue sends payload, which is required, and may send priority and maxAttempts.
    • Claim has the body {"leaseMs":30000}. Its response holds the lease token.
    • The last three routes send {"lease":"..."}. Heartbeat also sends leaseMs.
    • 409 means that the lease is wrong, expired or finished.

    Claim is a POST, because it changes state. An empty queue is a 204 and not an error.

    C

    The checkpoints

    15, 30 and 45 minutes
    bybuildproofif you are late
    15 minThe kit, renamed. Enqueue and claim over MemStore. The ordered list. The 204.TestPriorityThenOrderSkip the range checks. Add them in the last 5 minutes.
    30 minUpdate with the lease check. Complete, fail, heartbeat. Attempts and the failed state.TestFailRetriesThenStopsBuild complete first. Fail is then one more route with one more rule.
    45 minThe expiry loop inside claim. Race test with 100 parallel claims.TestExpiredLeaseReturnsTheJob, TestParallelClaimsKeep the mutex and say the rule out loud: "the read and the mark are one step."

    I keep a running service at each checkpoint. If I am late at 30 minutes, I keep the lease check and describe the retry.

    D

    The core idea

    four states, one lease
    queuedin the ordered listleasedone live tokendonefinished oncefailedno attempts leftclaimattempts + 1completelast tryheartbeatfail, or the lease expiresgoes behind jobs of its own priorityDashed paths have a branch: attempts left return the job, none left fail it.Expiry needs no timer. The next claim finds the old lease and acts on it.

    A job has four states. Two paths lead back to the queue, and both spend an attempt that claim already counted.

    E

    Why it fits

    computed from the files
    partvalue
    Lines, with tests448
    Typed characters9,883
    Typing at 500 a minute19:46
    Typing at 300 a minute32:57
    Left for thinking, at 500 a minute25:14
    Dependencies0
    • Build the store interface from the kit. It carries over to the talk.
    • In the room, keep every file in package main. Here main.go sits in its own folder, so the production version can import the build.

    Typed characters leave out imports, closing brackets, indentation and comments. Arithmetic, not a measurement of a person.

    I have rehearsed the kit part of this build. The new work is the lease logic.

    F

    store.go

    reference build
    store.gogo
    package build
    
    import (
    	"context"
    	"errors"
    	"slices"
    	"sort"
    	"sync"
    	"time"
    )
    
    var (
    	ErrInvalid  = errors.New("invalid")
    	ErrNotFound = errors.New("not found")
    	ErrConflict = errors.New("conflict")
    	ErrEmpty    = errors.New("queue is empty")
    )
    
    const (
    	Queued = "queued"
    	Leased = "leased"
    	Done   = "done"
    	Failed = "failed"
    )
    
    type Job struct {
    	ID          string    `json:"id"`
    	Queue       string    `json:"queue"`
    	Payload     string    `json:"payload"`
    	Priority    int       `json:"priority"`
    	Status      string    `json:"status"`
    	Attempts    int       `json:"attempts"`
    	MaxAttempts int       `json:"maxAttempts"`
    	Lease       string    `json:"lease,omitempty"`
    	LeaseUntil  time.Time `json:"leaseUntil,omitzero"`
    }
    
    // Release ends a lease: the job goes back to wait, or fails if it has no attempts left.
    func (j *Job) Release() {1
    	j.Status, j.Lease, j.LeaseUntil = Queued, "", time.Time{}
    	if j.Attempts >= j.MaxAttempts {
    		j.Status = Failed
    	}
    }
    
    type Store interface {
    	Add(ctx context.Context, job Job) error
    	Get(ctx context.Context, id string) (Job, error)
    	// Claim returns any expired jobs to their queues, then leases the next job in queue, or
    	// returns ErrEmpty.
    	Claim(ctx context.Context, queue, lease string, ttl time.Duration) (Job, error)
    	// Update runs fn on the job if lease is live, or returns ErrConflict. now is the store's clock.
    	Update(ctx context.Context, id, lease string, fn func(job *Job, now time.Time)) (Job, error)2
    }
    
    type MemStore struct {
    	mu      sync.Mutex
    	jobs    map[string]*Job
    	waiting map[string][]*Job // per queue, best first
    	leased  map[string]*Job
    }
    
    func NewMemStore() *MemStore {
    	return &MemStore{jobs: map[string]*Job{}, waiting: map[string][]*Job{}, leased: map[string]*Job{}}
    }
    
    // push puts a job behind every job of its own priority or higher.
    func (s *MemStore) push(job *Job) {
    	list := s.waiting[job.Queue]
    	i := sort.Search(len(list), func(i int) bool { return list[i].Priority < job.Priority3 })
    	s.waiting[job.Queue] = slices.Insert(list, i, job)
    }
    
    func (s *MemStore) Add(_ context.Context, job Job) error {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	s.jobs[job.ID] = &job
    	s.push(&job)
    	return nil
    }
    
    func (s *MemStore) Get(_ context.Context, id string) (Job, error) {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	job, ok := s.jobs[id]
    	if !ok {
    		return Job{}, ErrNotFound
    	}
    	out := *job
    	out.Lease = ""4
    	return out, nil
    }
    
    func (s *MemStore) Claim(_ context.Context, queue, lease string, ttl time.Duration) (Job, error) {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	now := time.Now()
    	for id, job := range s.leased {5
    		if !now.Before(job.LeaseUntil) {6
    			delete(s.leased, id)
    			if job.Release(); job.Status == Queued {
    				s.push(job)
    			}
    		}
    	}
    	list := s.waiting[queue]
    	if len(list) == 0 {
    		return Job{}, ErrEmpty
    	}
    	job := list[0]
    	s.waiting[queue] = list[1:]
    	job.Status, job.Lease, job.LeaseUntil = Leased, lease, now.Add(ttl)
    	job.Attempts++7
    	s.leased[job.ID] = job
    	return *job, nil
    }
    
    func (s *MemStore) Update(_ context.Context, id, lease string, fn func(*Job, time.Time)) (Job, error) {
    	s.mu.Lock()
    	defer s.mu.Unlock()
    	job, ok := s.jobs[id]
    	if !ok {
    		return Job{}, ErrNotFound
    	}
    	now := time.Now()
    	if job.Lease != lease || !now.Before(job.LeaseUntil) {8
    		return Job{}, ErrConflict
    	}
    	fn(job, now)
    	if job.Status != Leased {
    		delete(s.leased, id)
    	}
    	if job.Status == Queued {
    		s.push(job)
    	}
    	return *job, nil
    }
    
    1. 1Fail and expiry share this rule, so they cannot disagree about the last attempt.
    2. 2The store owns the clock and the lock. The service owns the rules. Postgres implements this same method.
    3. 3The first job of a lower priority. Inserting there keeps arrival order, and it sends a retry behind its peers.
    4. 4The token is a credential. Only the claim response shows it.
    5. 5The expiry check. It runs under the same lock as the claim, so one expired job goes to one worker.
    6. 6A lease ends at the exact instant of its expiry. Update uses the same test, so the two cannot overlap.
    7. 7Counted here, before the work. A worker that dies never reaches fail.
    8. 8Both tests matter. A finished job has no lease, and an expired lease must fail before any new claim runs.

    One mutex covers the list and the leases, so a claim is one step. Expiry is a loop at the top of claim, and no timer is needed.

    G

    service.go

    reference build
    service.gogo
    package build
    
    import (
    	"context"
    	"crypto/rand"
    	"fmt"
    	"time"
    )
    
    const (
    	maxQueue    = 64
    	maxPriority = 9
    	maxAttempts = 10
    	maxLeaseMs  = 3_600_000
    )
    
    type Service struct {
    	store Store
    }
    
    func NewService(store Store) *Service {
    	return &Service{store: store}
    }
    
    func checkQueue(queue string) error {
    	if len(queue) > maxQueue {
    		return fmt.Errorf("%w: queue is over %d bytes", ErrInvalid, maxQueue)
    	}
    	return nil
    }
    
    // duration reads leaseMs. The range check comes first: a huge number would overflow a Duration.
    func duration(ms int) (time.Duration, error) {
    	if ms < 1 || ms > maxLeaseMs {1
    		return 0, fmt.Errorf("%w: leaseMs must be from 1 to %d", ErrInvalid, maxLeaseMs)
    	}
    	return time.Duration(ms) * time.Millisecond, nil
    }
    
    func (s *Service) Enqueue(ctx context.Context, queue, payload string, priority, attempts int) (Job, error) {
    	if attempts == 0 {
    		attempts = 3
    	}
    	switch {
    	case payload == "":
    		return Job{}, fmt.Errorf("%w: payload is required", ErrInvalid)
    	case priority < 0 || priority > maxPriority:
    		return Job{}, fmt.Errorf("%w: priority must be from 0 to %d", ErrInvalid, maxPriority)
    	case attempts < 1 || attempts > maxAttempts:
    		return Job{}, fmt.Errorf("%w: maxAttempts must be from 1 to %d", ErrInvalid, maxAttempts)
    	}
    	if err := checkQueue(queue); err != nil {
    		return Job{}, err
    	}
    	job := Job{ID: rand.Text(), Queue: queue, Payload: payload, Priority: priority, Status: Queued, MaxAttempts: attempts}
    	return job, s.store.Add(ctx, job)
    }
    
    func (s *Service) Get(ctx context.Context, id string) (Job, error) {
    	return s.store.Get(ctx, id)
    }
    
    // Claim gives each lease a new token, so a worker that lost a lease cannot act on the next one.
    func (s *Service) Claim(ctx context.Context, queue string, ms int) (Job, error) {
    	ttl, err := duration(ms)
    	if err != nil {
    		return Job{}, err
    	}
    	if err := checkQueue(queue); err != nil {
    		return Job{}, err
    	}
    	return s.store.Claim(ctx, queue, rand.Text(), ttl)2
    }
    
    func (s *Service) Heartbeat(ctx context.Context, id, lease string, ms int) (Job, error) {
    	ttl, err := duration(ms)
    	if err != nil {
    		return Job{}, err
    	}
    	return s.store.Update(ctx, id, lease, func(job *Job, now time.Time) {
    		job.LeaseUntil = now.Add(ttl)3
    	})
    }
    
    func (s *Service) Complete(ctx context.Context, id, lease string) (Job, error) {
    	return s.store.Update(ctx, id, lease, func(job *Job, _ time.Time) {
    		job.Status, job.Lease, job.LeaseUntil = Done, "", time.Time{}
    	})
    }
    
    func (s *Service) Fail(ctx context.Context, id, lease string) (Job, error) {
    	return s.store.Update(ctx, id, lease, func(job *Job, _ time.Time) {
    		job.Release()4
    	})
    }
    
    1. 1Check the range before the multiply. A huge number would overflow a Duration and turn into a short lease.
    2. 2A new token per lease. The old holder cannot act on the new lease.
    3. 3A heartbeat sets a new end from now. It does not add to the old one, so a worker cannot bank time.
    4. 4The store sees the new status and returns the job to the queue.

    The service holds the limits and the meaning of each call. Each call is a small function passed to Update.

    H

    handler.go and main.go

    reference build
    handler.gogo
    package build
    
    import (
    	"context"
    	"encoding/json"
    	"errors"
    	"fmt"
    	"log"
    	"net/http"
    )
    
    type leaseBody struct {
    	Lease   string
    	LeaseMs int
    }
    
    func readLease(r *http.Request) (leaseBody, error) {
    	var body leaseBody
    	if err := readJSON(r, &body); err != nil {
    		return body, err
    	}
    	if body.Lease == "" {1
    		return body, fmt.Errorf("%w: lease is required", ErrInvalid)
    	}
    	return body, nil
    }
    
    func Handler(svc *Service) http.Handler {
    	end := func(fn func(context.Context, string, string) (Job, error)) http.Handler {2
    		return route(200, func(r *http.Request) (any, error) {
    			body, err := readLease(r)
    			if err != nil {
    				return nil, err
    			}
    			return fn(r.Context(), r.PathValue("id"), body.Lease)
    		})
    	}
    
    	mux := http.NewServeMux()
    	mux.Handle("POST /queues/{queue}/jobs", route(201, func(r *http.Request) (any, error) {
    		var body struct {
    			Payload               string
    			Priority, MaxAttempts int
    		}
    		if err := readJSON(r, &body); err != nil {
    			return nil, err
    		}
    		return svc.Enqueue(r.Context(), r.PathValue("queue"), body.Payload, body.Priority, body.MaxAttempts)
    	}))
    	mux.Handle("POST /queues/{queue}/claim", route(200, func(r *http.Request) (any, error) {
    		var body leaseBody
    		if err := readJSON(r, &body); err != nil {
    			return nil, err
    		}
    		return svc.Claim(r.Context(), r.PathValue("queue"), body.LeaseMs)
    	}))
    	mux.Handle("GET /jobs/{id}", route(200, func(r *http.Request) (any, error) {
    		return svc.Get(r.Context(), r.PathValue("id"))
    	}))
    	mux.Handle("POST /jobs/{id}/heartbeat", route(200, func(r *http.Request) (any, error) {
    		body, err := readLease(r)
    		if err != nil {
    			return nil, err
    		}
    		return svc.Heartbeat(r.Context(), r.PathValue("id"), body.Lease, body.LeaseMs)
    	}))
    	mux.Handle("POST /jobs/{id}/complete", end(svc.Complete))
    	mux.Handle("POST /jobs/{id}/fail", end(svc.Fail))
    	return mux
    }
    
    func route(status int, fn func(*http.Request) (any, error)) http.Handler {
    	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    		code := status
    		v, err := fn(r)
    		if err != nil {
    			code, v = failure(err)
    		}
    		w.Header().Set("Content-Type", "application/json")
    		w.WriteHeader(code)
    		if code == 204 {3
    			return
    		}
    		if err := json.NewEncoder(w).Encode(v); err != nil {
    			log.Print(err)
    		}
    	})
    }
    
    func readJSON(r *http.Request, v any) error {
    	if err := json.NewDecoder(r.Body).Decode(v); err != nil {
    		return fmt.Errorf("%w: %v", ErrInvalid, err)
    	}
    	return nil
    }
    
    func failure(err error) (int, any) {
    	status := 500
    	switch {
    	case errors.Is(err, ErrEmpty):
    		status = 204
    	case errors.Is(err, ErrInvalid):
    		status = 400
    	case errors.Is(err, ErrNotFound):
    		status = 404
    	case errors.Is(err, ErrConflict):
    		status = 409
    	default:
    		log.Print(err)
    		err = errors.New("internal error")
    	}
    	return status, map[string]string{"error": err.Error()}
    }
    
    1. 1A missing lease is the client's bug, so 400. A wrong lease is a race, so 409.
    2. 2Complete and Fail share one signature, so they share one route helper.
    3. 3A 204 must have no body.
    4. 4An empty queue is a normal answer. Workers poll, and an error status would fill the logs.
    main.gogo
    // Command main serves the 45-minute job queue.
    package main
    
    import (
    	"log"
    	"net/http"
    
    	"github.com/rudrite/system-design/arena/exercises/jobqueue/build"
    )
    
    func main() {
    	handler := build.Handler(build.NewService(build.NewMemStore()))
    	log.Fatal(http.ListenAndServe(":8080", handler))
    }
    

    Six routes. An empty queue maps to 204 in the error table, so the claim route has one path.

    I

    build_test.go

    type this part too
    build_test.gogo
    package build
    
    import (
    	"encoding/json"
    	"net/http"
    	"net/http/httptest"
    	"strings"
    	"sync"
    	"testing"
    	"time"
    )
    
    func do(h http.Handler, method, path, body string) (int, Job) {
    	w := httptest.NewRecorder()
    	h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
    	var job Job
    	_ = json.Unmarshal(w.Body.Bytes(), &job) // a 204 has no body: job stays empty
    	return w.Code, job
    }
    
    func newHandler() http.Handler {
    	return Handler(NewService(NewMemStore()))
    }
    
    func TestPriorityThenOrder(t *testing.T) {
    	h := newHandler()
    	for _, body := range []string{`{"payload":"low"}`, `{"payload":"a","priority":5}`, `{"payload":"b","priority":5}`1} {
    		if status, _ := do(h, "POST", "/queues/q/jobs", body); status != 201 {
    			t.Fatal(status)
    		}
    	}
    	for _, want := range []string{"a", "b", "low"} {
    		if _, job := do(h, "POST", "/queues/q/claim", `{"leaseMs":1000}`); job.Payload != want {
    			t.Errorf("got %q, want %q", job.Payload, want)
    		}
    	}
    	if status, _ := do(h, "POST", "/queues/q/claim", `{"leaseMs":1000}`); status != 204 {
    		t.Errorf("empty queue: %d", status)
    	}
    }
    
    func TestFailRetriesThenStops(t *testing.T) {
    	h := newHandler()
    	do(h, "POST", "/queues/q/jobs", `{"payload":"x","maxAttempts":2}`)
    	for _, want := range []string{Queued, Failed} {2
    		_, job := do(h, "POST", "/queues/q/claim", `{"leaseMs":1000}`)
    		_, job = do(h, "POST", "/jobs/"+job.ID+"/fail", `{"lease":"`+job.Lease+`"}`)
    		if job.Status != want {
    			t.Errorf("got %q, want %q", job.Status, want)
    		}
    	}
    }
    
    func TestExpiredLeaseReturnsTheJob(t *testing.T) {
    	h := newHandler()
    	do(h, "POST", "/queues/q/jobs", `{"payload":"x"}`)
    	_, first := do(h, "POST", "/queues/q/claim", `{"leaseMs":5}`)
    	time.Sleep(10 * time.Millisecond)3
    	stale := `{"lease":"` + first.Lease + `"}`
    	if status, _ := do(h, "POST", "/jobs/"+first.ID+"/complete", stale); status != 409 {
    		t.Errorf("complete after expiry: %d", status)
    	}
    	_, second := do(h, "POST", "/queues/q/claim", `{"leaseMs":1000}`)
    	if second.ID != first.ID || second.Attempts != 2 {
    		t.Errorf("got %+v", second)
    	}
    }
    
    func TestParallelClaims(t *testing.T) {
    	h := newHandler()
    	for range 100 {
    		do(h, "POST", "/queues/q/jobs", `{"payload":"x"}`)
    	}
    	var mu sync.Mutex
    	seen := map[string]bool{}
    	var wg sync.WaitGroup
    	for range 100 {
    		wg.Go(func() {
    			_, job := do(h, "POST", "/queues/q/claim", `{"leaseMs":60000}`)
    			mu.Lock()
    			defer mu.Unlock()
    			seen[job.ID] = true
    		})
    	}
    	wg.Wait()
    	if len(seen) != 100 {4
    		t.Errorf("%d distinct jobs, want 100", len(seen))
    	}
    }
    
    1. 1Equal priorities, so the order proves arrival order.
    2. 2maxAttempts is 2: the first fail retries, and the second stops.
    3. 3Real time, kept short. The deeper tests use a fake clock.
    4. 4A map of IDs: a job claimed twice leaves fewer than 100 entries.

    The last test is the one that matters. Run it with -race. 100 claims must give 100 different jobs.

    J

    The grader agrees

    33 checks, saved from a real run
    reportsaved output
    arena run jobqueue --base http://localhost:8080
    
    correctness
      PASS  get returns what enqueue stored
      PASS  claim leases the job
      PASS  the highest priority goes first
      PASS  equal priorities go in order of arrival
      PASS  queues do not mix
      PASS  complete ends the job
      PASS  fail puts the job back for another attempt
      PASS  a retry goes behind jobs of its own priority
      PASS  fail with no attempts left ends the job
      PASS  an expired lease returns the job
      PASS  an expired lease with no attempts left fails the job
      PASS  heartbeat keeps the lease alive
    
    status codes
      PASS  enqueue is 201 and returns an id
      PASS  claim on an empty queue is 204
      PASS  an unknown job is 404
      PASS  a wrong lease is 409
      PASS  an expired lease is 409, before any new claim
      PASS  the old holder gets 409 and the new holder finishes
      PASS  a finished job is 409
    
    validation
      PASS  malformed JSON is 400
      PASS  a missing payload is 400
      PASS  a value of the wrong type is 400
      PASS  a priority outside 0 to 9 is 400
      PASS  maxAttempts outside 1 to 10 is 400
      PASS  leaseMs outside 1 to 3600000 is 400
      PASS  a missing lease is 400
      PASS  a queue name over 64 bytes is 400
    
    concurrency
      PASS  100 parallel enqueues all land
      PASS  100 parallel claims on 100 jobs: no job goes twice
      PASS  100 parallel claims on 10 jobs: exactly 10 win
      PASS  100 parallel claims on one expired job: exactly one wins
      PASS  100 parallel completes of one lease: exactly one wins
      PASS  100 workers finish 100 jobs, each exactly once
    
    33 checks: 33 passed, 0 failed

    All checks pass, with 100 parallel claims and a real expired lease.

    K

    A race it catches

    two overlapping claims read one head

    A test server reads the head of the list, pauses, then marks the job. Each step takes the lock, so no data race exists.

    reportsaved output, failures only
      FAIL  100 parallel claims on 100 jobs: no job goes twice
            this job is out on a live lease to another worker
      FAIL  100 parallel claims on 10 jobs: exactly 10 win
            this job is out on a live lease to another worker
      FAIL  100 parallel claims on one expired job: exactly one wins
            36 of 100 claims won, want exactly 1
      FAIL  100 workers finish 100 jobs, each exactly once
            want status 200, got 409
    
    33 checks: 29 passed, 4 failed
    choicestatus
    One lock across read and markApproved
    A lock for the read and a lock for the markNot approved
    A new token per leaseApproved
    The worker name as the leaseNot approved
    A timer per leaseSay the cost
    Expiry checked at claimApproved
    An attempt counted at failNot approved

    Every sequential check passes on this server. Only parallel claims show the bug, and the race detector stays quiet.

    L

    The talk map

    the second 45 minutes
    the interviewer asksthe answergoes deeper
    Run two instances. What breaks?Each mutex covers one process, and each list holds different jobs. A worker on the second instance cannot finish a lease from the first. All of it moves to Postgres, and the row lock replaces the mutex.T4 Locks in the database
    What does SKIP LOCKED buy?With plain FOR UPDATE, every claim wants the head row, so claims run one at a time. SKIP LOCKED passes a row another claim holds and takes the next free one. A test proves both behaviours.T4 Locks in the database
    Why a lease and not a lock?A lock has an owner that can die while holding it. A lease ends by itself, so a dead worker frees the job. The price is that a slow worker also loses it, so long jobs must heartbeat.T6 Distributed locks
    A worker stalls past its lease, then writes to another system.The 409 stops only the call to this service. The other system still takes the write. Pass a number that grows with each lease, so that system can refuse an old one. That number is a fencing token.T6 Distributed locks
    Is a job run exactly once?No. A worker can do the work and die before complete, so the job runs again. Delivery is at least once. The job must be idempotent, for example with its ID as the key of its effect.T9 Exactly-once
    A table, or a broker?A table lets the enqueue share a transaction with the business write, and it gives priorities. A broker or a log gives far higher throughput and replay. I start with the table and move when it limits me.B6 Queues and logs
    One job crashes every worker that takes it.It never calls fail, so only the attempt count can stop it. Claim counts the attempt before the work starts. After the limit, the job goes to failed. An operator reads those rows and can requeue them.O2 Resilience patterns
    Retries come back at once. Is that safe?Not against a system that is down. Add a run_at column, set it with exponential backoff and jitter, and filter on it in the claim. This reference leaves that out, so I name it as the next change.O2 Resilience patterns
    How do you run a job at 9:00 tomorrow, or every hour?The same run_at column covers one job in the future. A schedule table adds repeats. A unique key on the schedule and fire time stops two schedulers from adding the same job twice.C17 Job scheduler
    High priority work never stops arriving.Low priority jobs starve, because the order is strict. One tenant can also fill a queue. Give each tenant a queue and take from them in turn, or raise the priority of old jobs.C17 Job scheduler
    The table reaches a hundred million rows.The partial indexes hold only queued and leased rows, so finished rows do not slow a claim. Each claim still leaves a dead row for vacuum. Move finished jobs out of the table on a schedule.D2 Indexes
    What goes on the dashboard?Queue depth and the age of the oldest queued job come first. Then expired leases, and the count of failed jobs. Age shows that workers are behind, even when depth looks normal.O3 Observability

    I start from what the build lacks: durability, two instances, then what a lease cannot promise. I name each limit before the interviewer does.

    M

    The production shape

    what moves out of the process
    workersinstance 1auth, buildinstance 2auth, buildPostgres: jobs, by jobs_readyjob 7, priority 9claim A has the lockjob 3, priority 5claim B skips to herejob 9, priority 5claim C skips to herejob 2, priority 0freeEach claim locks one row for one short statement, then commits.The lease is a value in the row. No lock stays held while a worker runs a job.

    Instances hold no state. A claim is one short statement, so a long job holds no lock and no connection.

    N

    What changes

    from build to production
    toolbuildproduction
    PostgresOrdered list and mutexjobs table, partial index, FOR UPDATE SKIP LOCKED
    PostgresLoop over leases at claimOne UPDATE at claim, with SKIP LOCKED
    Postgrestime.Now in the processnow() in the database, for every instance
    ServiceNo authBearer tokens
    ServiceNo metricsRequests and time by route and status; health route
    ServiceListenAndServeTimeouts, a body limit, drain on SIGTERM

    Tested: production passes the same 33 grader checks. The real binary passes them over a socket, then exits cleanly on SIGTERM. Auth and metrics are the ones from E1.

    One interface, one new implementation, and a wrapper around the same handler. The service file does not change.

    O

    The diff

    build to production

    store.go, service.go and handler.go of the build are imported as they are. The production package adds the files below.

    main.go+63 -4
    + // Command main serves the production job queue. It reads DATABASE_URL, API_TOKENS
    + // (owner:token,owner:token) and ADDR, which defaults to :8080.
    - // Command main serves the 45-minute job queue.
      package main
      
      import (
    + 	"cmp"
    + 	"context"
    + 	"errors"
      	"log"
      	"net/http"
    + 	"os"
    + 	"os/signal"
    + 	"syscall"
    + 	"time"
      
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + 
    + 	"github.com/rudrite/system-design/arena/exercises/jobqueue/prod"
    + 	kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
    - 	"github.com/rudrite/system-design/arena/exercises/jobqueue/build"
      )
      
      func main() {
    + 	if err := run(); err != nil {
    + 		log.Fatal(err)
    + 	}
    + }
    + 
    + func run() error {
    + 	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    + 	defer stop()
    + 
    + 	pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
    + 	if err != nil {
    + 		return err
    + 	}
    + 	defer pool.Close()
    + 	if err := prod.Migrate(ctx, pool); err != nil {
    + 		return err
    + 	}
    + 	tokens, err := kv.ParseTokens(os.Getenv("API_TOKENS"))
    + 	if err != nil {
    + 		return err
    + 	}
    + 	handler := prod.Handler(pool, tokens, kv.NewMetrics())
    + 
    + 	srv := &http.Server{
    + 		Addr:              cmp.Or(os.Getenv("ADDR"), ":8080"),
    + 		Handler:           handler,
    + 		ReadHeaderTimeout: 5 * time.Second,
    + 		ReadTimeout:       10 * time.Second,
    + 		WriteTimeout:      10 * time.Second,
    + 		IdleTimeout:       60 * time.Second,
    + 	}
    + 	failed := make(chan error, 1)
    + 	go func() { failed <- srv.ListenAndServe() }()
    + 
    + 	select {
    + 	case err := <-failed:
    + 		return err
    + 	case <-ctx.Done():
    + 	}
    + 	// SIGTERM: stop accepting, finish what is running, then exit. A lease held by a worker stays in
    + 	// the database, and the worker can use any instance to finish.
    + 	drain, cancel := context.WithTimeout(context.Background(), 20*time.Second)
    + 	defer cancel()
    + 	if err := srv.Shutdown(drain); err != nil {
    + 		return err
    + 	}
    + 	if err := <-failed; !errors.Is(err, http.ErrServerClosed) {
    + 		return err
    + 	}
    + 	return nil
    - 	handler := build.Handler(build.NewService(build.NewMemStore()))
    - 	log.Fatal(http.ListenAndServe(":8080", handler))
      }
    schema.sqlnew file
    CREATE SEQUENCE IF NOT EXISTS job_seq;
    
    CREATE TABLE IF NOT EXISTS jobs (
        id           text PRIMARY KEY,
        queue        text NOT NULL,
        payload      text NOT NULL,
        priority     smallint NOT NULL CHECK (priority BETWEEN 0 AND 9),
        status       text NOT NULL CHECK (status IN ('queued', 'leased', 'done', 'failed')),
        attempts     int NOT NULL DEFAULT 0,
        max_attempts int NOT NULL,
        seq          bigint NOT NULL DEFAULT nextval('job_seq'),
        lease        text,
        lease_until  timestamptz
    );
    
    -- Partial indexes: they hold only the rows a claim looks at, so finished jobs cost them nothing.
    CREATE INDEX IF NOT EXISTS jobs_ready ON jobs (queue, priority DESC, seq) WHERE status = 'queued';
    CREATE INDEX IF NOT EXISTS jobs_expiring ON jobs (lease_until) WHERE status = 'leased';
    pgstore: implements Storenew file, +136
    + // Package prod is the job queue made production grade. It imports the 45-minute build and replaces
    + // the in-memory store behind its interface. The service and the handler do not change.
    + package prod
    + 
    + import (
    + 	"context"
    + 	"errors"
    + 	"fmt"
    + 	"time"
    + 
    + 	"github.com/jackc/pgx/v5"
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + 
    + 	"github.com/rudrite/system-design/arena/exercises/jobqueue/build"
    + )
    + 
    + // PGStore implements build.Store on Postgres. Every time comes from the database clock, so two
    + // instances with different clocks agree on when a lease ends.
    + type PGStore struct {
    + 	pool *pgxpool.Pool
    + }
    + 
    + // NewPGStore returns a store on pool.
    + func NewPGStore(pool *pgxpool.Pool) *PGStore {
    + 	return &PGStore{pool: pool}
    + }
    + 
    + const columns = `id, queue, payload, priority, status, attempts, max_attempts,
    +     COALESCE(lease, ''), lease_until`
    + 
    + func scan(row pgx.Row, more ...any) (build.Job, error) {
    + 	var job build.Job
    + 	var until *time.Time
    + 	err := row.Scan(append([]any{&job.ID, &job.Queue, &job.Payload, &job.Priority, &job.Status,
    + 		&job.Attempts, &job.MaxAttempts, &job.Lease, &until}, more...)...)
    + 	if errors.Is(err, pgx.ErrNoRows) {
    + 		return job, build.ErrNotFound
    + 	}
    + 	if err != nil {
    + 		return job, fmt.Errorf("scan job: %w", err)
    + 	}
    + 	if until != nil {
    + 		job.LeaseUntil = *until
    + 	}
    + 	return job, nil
    + }
    + 
    + // Add stores a new job.
    + func (s *PGStore) Add(ctx context.Context, job build.Job) error {
    + 	_, err := s.pool.Exec(ctx, `
    + INSERT INTO jobs (id, queue, payload, priority, status, max_attempts)
    + VALUES ($1, $2, $3, $4, $5, $6)`, job.ID, job.Queue, job.Payload, job.Priority, job.Status, job.MaxAttempts)
    + 	if err != nil {
    + 		return fmt.Errorf("add job: %w", err)
    + 	}
    + 	return nil
    + }
    + 
    + // Get returns a job without its lease token.
    + func (s *PGStore) Get(ctx context.Context, id string) (build.Job, error) {
    + 	job, err := scan(s.pool.QueryRow(ctx, `SELECT `+columns+` FROM jobs WHERE id = $1`, id))
    + 	job.Lease = ""
    + 	return job, err
    + }
    + 
    + // sweep returns expired jobs to their queues, as the mutex-guarded loop does in the build. SKIP
    + // LOCKED lets parallel claims share the work: each one takes the rows nobody holds.
    + const sweep = `
    + UPDATE jobs
    + SET lease = NULL, lease_until = NULL, seq = nextval('job_seq'),
    +     status = CASE WHEN attempts >= max_attempts THEN 'failed' ELSE 'queued' END
    + WHERE id IN (
    +     SELECT id FROM jobs
    +     WHERE status = 'leased' AND lease_until <= now()
    +     FOR UPDATE SKIP LOCKED)`
    + 
    + // next is the row a claim wants. It is the head of the build's ordered list, and SKIP LOCKED makes
    + // each parallel claim take a different row, so none waits for another.
    + const next = `
    + SELECT id FROM jobs
    + WHERE queue = $1 AND status = 'queued'
    + ORDER BY priority DESC, seq
    + LIMIT 1
    + FOR UPDATE SKIP LOCKED`
    + 
    + const claim = `
    + UPDATE jobs
    + SET status = 'leased', attempts = attempts + 1, lease = $2,
    +     lease_until = now() + make_interval(secs => $3)
    + WHERE id = (` + next + `)
    + RETURNING ` + columns
    + 
    + // Claim runs in two statements. The sweep commits alone, so a job it returns is visible to the
    + // claim, and a crash between them loses nothing.
    + func (s *PGStore) Claim(ctx context.Context, queue, lease string, ttl time.Duration) (build.Job, error) {
    + 	if _, err := s.pool.Exec(ctx, sweep); err != nil {
    + 		return build.Job{}, fmt.Errorf("sweep leases: %w", err)
    + 	}
    + 	job, err := scan(s.pool.QueryRow(ctx, claim, queue, lease, ttl.Seconds()))
    + 	if errors.Is(err, build.ErrNotFound) {
    + 		return build.Job{}, build.ErrEmpty
    + 	}
    + 	return job, err
    + }
    + 
    + // Update takes the row lock, checks the lease, and writes back what fn changed. A claim that wants
    + // this row skips it until the commit.
    + func (s *PGStore) Update(ctx context.Context, id, lease string, fn func(*build.Job, time.Time)) (build.Job, error) {
    + 	var job build.Job
    + 	err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
    + 		var now time.Time
    + 		var err error
    + 		job, err = scan(tx.QueryRow(ctx, `SELECT `+columns+`, now() FROM jobs WHERE id = $1 FOR UPDATE`, id), &now)
    + 		if err != nil {
    + 			return err
    + 		}
    + 		if job.Lease != lease || !now.Before(job.LeaseUntil) {
    + 			return build.ErrConflict
    + 		}
    + 		fn(&job, now)
    + 		var until *time.Time
    + 		if !job.LeaseUntil.IsZero() {
    + 			until = &job.LeaseUntil
    + 		}
    + 		_, err = tx.Exec(ctx, `
    + UPDATE jobs
    + SET status = $2, lease = NULLIF($3, ''), lease_until = $4,
    +     seq = CASE WHEN $2 = 'queued' THEN nextval('job_seq') ELSE seq END
    + WHERE id = $1`, id, job.Status, job.Lease, until)
    + 		if err != nil {
    + 			return fmt.Errorf("update job: %w", err)
    + 		}
    + 		return nil
    + 	})
    + 	return job, err
    + }
    server: wraps the build's handlernew file, +48
    + package prod
    + 
    + import (
    + 	"context"
    + 	_ "embed"
    + 	"fmt"
    + 	"net/http"
    + 	"time"
    + 
    + 	"github.com/jackc/pgx/v5/pgxpool"
    + 
    + 	"github.com/rudrite/system-design/arena/exercises/jobqueue/build"
    + 	kv "github.com/rudrite/system-design/arena/exercises/kvstore/prod"
    + )
    + 
    + //go:embed schema.sql
    + var schema string
    + 
    + // Migrate applies the schema. It is safe to run twice.
    + func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
    + 	if _, err := pool.Exec(ctx, schema); err != nil {
    + 		return fmt.Errorf("apply schema: %w", err)
    + 	}
    + 	return nil
    + }
    + 
    + // maxBody limits a request body. A larger one fails to decode and answers 400.
    + const maxBody = 1 << 20
    + 
    + // Handler serves the API behind auth, plus the two routes an operator needs. Auth and metrics come
    + // from the key-value exercise, unchanged.
    + func Handler(pool *pgxpool.Pool, tokens kv.Tokens, metrics *kv.Metrics) http.Handler {
    + 	api := build.Handler(build.NewService(NewPGStore(pool)))
    + 
    + 	mux := http.NewServeMux()
    + 	mux.Handle("/", metrics.Wrap(kv.Auth(tokens, http.MaxBytesHandler(api, maxBody))))
    + 	mux.Handle("GET /metrics", metrics)
    + 	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
    + 		ctx, cancel := context.WithTimeout(r.Context(), time.Second)
    + 		defer cancel()
    + 		if err := pool.Ping(ctx); err != nil {
    + 			http.Error(w, "database unreachable", http.StatusServiceUnavailable)
    + 			return
    + 		}
    + 		w.WriteHeader(http.StatusNoContent)
    + 	})
    + 	return mux
    + }

    The heart of this diff is two SQL statements: the sweep and the claim. They do what the mutex did.

    P

    Drill

    predict, then reveal

    0 of 10 known

    1. Your claim reads the head of the list, unlocks, then marks the job leased under a second lock. What happens?

    2. A worker holds a job. Its lease ends. No other worker has claimed yet. It calls complete. What is the answer?

    3. Why does each claim get a new random token, and not the worker name?

    4. Why does the attempt count go up at claim and not at fail?

    5. Why an ordered list and not container/heap?

    6. Claim scans every leased job. What does that cost, and when does it matter?

    7. Why does the sweep use SKIP LOCKED too?

    8. Why does the sweep commit before the claim, in two statements?

    9. Why does production read the time from the database?

    10. GET shows a job as leased after its lease has ended. Is this a bug?

    Q

    Numbers to say

    from the files and tests
    build
    448 lines with tests, 19:46 of typing at 100 words a minute.
    checks
    33 grader checks, in 4 groups.
    race
    100 parallel claims on 100 jobs; 100 different jobs go out.
    expiry race
    100 parallel claims on one expired job; exactly one wins.
    attempts
    3 by default, 10 at most.
    lease
    1 ms to 1 hour, set by the worker.
    body limit
    1 MiB in production.

    Design values from the tested code, not load measurements.