Gin and your data · 7 MIN READ
Long work behind 202 Accepted in Gin: a bounded queue, fixed workers, a job resource and an honest 503
Accept slow work with 202 and a job Location, bound it with a queue and a fixed worker pool, refuse overload with 503 and Retry-After, and keep jobs running after the request ends.
Some requests ask for work that takes longer than any sensible request budget: a monthly report, a re-index, a large import. Holding the connection open ties up a goroutine, a proxy slot and the client's patience, and a timeout halfway leaves the client unsure whether anything happened. The asynchronous pattern splits the work from the request: the POST validates and enqueues, answers 202 Accepted with the URL of a job resource, and the client polls that resource until it reports a result or a failure.
gin · A MAP OF THE IDEA
- Validate, then enqueue
- Answer 202 + Location
- Workers run the job
- Client polls the job
Useful when
- Request latency stays small whatever the job costs.
- Overload is explicit: a bounded queue and a 503 with Retry-After.
Watch out
- An in-memory queue loses every job on restart.
- Guessable job IDs leak other users' results without owner checks.
Implementation & operation cost: A job store, a worker pool with its own shutdown, polling traffic and result retention; durability adds a jobs table, leases and idempotent work.
What 202 Accepted promises
RFC 9110 defines 202 as accepted for processing, with processing not yet complete and possibly never completing; the response ought to describe the request's current status and point to a status monitor. In practice that means three things. Everything that can be rejected synchronously is rejected before the 202: malformed input, missing permission and an exhausted quota get a 4xx immediately, because after a 202 the job resource is the only channel left. The 202 carries a Location header with the job URL; RFC 9110 defines Location for 201 and redirects, and using it with 202 is a widespread convention clients expect. And the job resource has a small, closed lifecycle: queued, running, then succeeded with a link to the result or failed with a public error message. Terminal states never change, so a client can stop polling as soon as it sees one.
A pool with two workers and room for one more
Pool owns the job records, a buffered channel as the queue and a fixed set of workers started with WaitGroup.Go. Submit records and enqueues a job in one critical section and never blocks; the handler turns its refusal into a 503. main holds jobs inside the work function with two channels: started tells main that a worker has picked a job up, and release lets one job finish. That fixes the order of every observable state without a single sleep.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
)
type Job struct {
ID string `json:"id"`
Status string `json:"status"` // queued, running, succeeded, failed
Result string `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
type task struct {
id, month string
ctx context.Context // request values without request cancellation
}
var errBusy = errors.New("queue full or shutting down")
// Pool is a fixed set of workers reading one bounded queue.
type Pool struct {
mu sync.Mutex
jobs map[string]*Job
queue chan task
closed bool
last int
wg sync.WaitGroup
budget time.Duration
work func(ctx context.Context, month string) error
}
func NewPool(workers, depth int, budget time.Duration, work func(context.Context, string) error) *Pool {
p := &Pool{jobs: map[string]*Job{}, queue: make(chan task, depth), budget: budget, work: work}
for range workers {
p.wg.Go(func() {
for t := range p.queue {
p.update(t.id, func(j *Job) { j.Status = "running" })
err := p.execute(t)
p.update(t.id, func(j *Job) {
if err != nil {
j.Status, j.Error = "failed", err.Error()
} else {
j.Status, j.Result = "succeeded", "/reports/"+t.id+"/result"
}
})
}
})
}
return p
}
// execute gives each job its own deadline and turns a panic into a failed job.
func (p *Pool) execute(t task) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("job panicked: %v", r)
}
}()
ctx, cancel := context.WithTimeout(t.ctx, p.budget)
defer cancel()
return p.work(ctx, t.month)
}
func (p *Pool) Submit(reqCtx context.Context, month string) (Job, error) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return Job{}, errBusy
}
id := strconv.Itoa(p.last + 1)
select {
case p.queue <- task{id: id, month: month, ctx: context.WithoutCancel(reqCtx)}:
p.last++
p.jobs[id] = &Job{ID: id, Status: "queued"} // workers wait for p.mu, so this lands first
return *p.jobs[id], nil
default:
return Job{}, errBusy
}
}
func (p *Pool) update(id string, f func(*Job)) {
p.mu.Lock()
defer p.mu.Unlock()
f(p.jobs[id])
}
func (p *Pool) Get(id string) (Job, bool) {
p.mu.Lock()
defer p.mu.Unlock()
j, ok := p.jobs[id]
if !ok {
return Job{}, false
}
return *j, true
}
// Shutdown stops intake, lets workers drain the queue and waits for them.
func (p *Pool) Shutdown() {
p.mu.Lock()
p.closed = true
close(p.queue)
p.mu.Unlock()
p.wg.Wait()
}
func createReport(p *Pool) gin.HandlerFunc {
return func(c *gin.Context) {
var in struct {
Month string `json:"month" binding:"required,datetime=2006-01"`
}
if err := c.ShouldBindJSON(&in); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "month must look like 2026-10"})
return
}
job, err := p.Submit(c.Request.Context(), in.Month)
if err != nil {
c.Header("Retry-After", "30")
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "report queue is full"})
return
}
c.Header("Location", "/jobs/"+job.ID)
c.JSON(http.StatusAccepted, job)
}
}
func getJob(p *Pool) gin.HandlerFunc {
return func(c *gin.Context) {
job, ok := p.Get(c.Param("id"))
if !ok {
c.JSON(http.StatusNotFound, gin.H{"error": "no such job"})
return
}
c.JSON(http.StatusOK, job)
}
}
func main() {
gin.SetMode(gin.TestMode)
started := make(chan string)
release := make(chan struct{})
work := func(ctx context.Context, month string) error {
started <- month
<-release
if err := ctx.Err(); err != nil {
return err // a job built on c.Request.Context() would stop here
}
if month == "2026-09" {
return errors.New("ledger archive offline")
}
return nil
}
pool := NewPool(2, 1, time.Minute, work)
r := gin.New()
r.POST("/reports", createReport(pool))
r.GET("/jobs/:id", getJob(pool))
post := func(month string) context.Context {
ctx, cancel := context.WithCancel(context.Background())
req := httptest.NewRequest("POST", "/reports", strings.NewReader(`{"month":"`+month+`"}`)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
cancel() // net/http cancels the request context when ServeHTTP returns
hdr := ""
if v := w.Header().Get("Location"); v != "" {
hdr = " Location: " + v
}
if v := w.Header().Get("Retry-After"); v != "" {
hdr = " Retry-After: " + v
}
fmt.Printf("POST %s -> %d%s %s\n", month, w.Code, hdr, w.Body.String())
return ctx
}
get := func(id string) {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/jobs/"+id, nil))
fmt.Printf("GET /jobs/%s -> %d %s\n", id, w.Code, w.Body.String())
}
reqCtx := post("2026-10")
fmt.Println("request context of job 1 after the 202:", reqCtx.Err())
<-started // job 1 is running on one worker
post("2026-09")
<-started // job 2 is running on the other
post("2026-08") // waits in the queue
post("2026-07") // queue full
post("October")
get("1")
get("3")
release <- struct{}{} // one worker finishes and takes job 3
<-started
release <- struct{}{}
release <- struct{}{}
pool.Shutdown()
fmt.Println("shutdown: queue drained, workers joined")
for _, id := range []string{"1", "2", "3", "4"} {
get(id)
}
}Job 1 starts on the first worker and job 2 on the second, so job 3 waits in the one-slot queue and the fourth POST finds it full: 503 with Retry-After and no job created, which the final 404 confirms. October fails the datetime=2006-01 rule before any job exists. The second line matters most: once ServeHTTP has returned, the request context is canceled, yet job 1 later succeeds, because its task carries context.WithoutCancel of that context. The first release frees one worker, which takes job 3 and reports through started; the next two releases let the remaining jobs finish. Shutdown closes the queue under the lock and waits for both workers, so every job is terminal before the final GETs: job 2 failed because its work returned an error, and the other two succeeded and link to their results.
Bound the queue, fix the workers, refuse early
The channel capacity is the backlog you are willing to promise, and the worker count is the concurrency the downstream system can sustain; the bounded-work lesson shows how to size both. Submit uses select with a default case, so a full queue is an immediate answer rather than a blocked handler. Waiting for space would only move the queue into parked goroutines, where nothing bounds or measures it. Answer 503 Service Unavailable with Retry-After so clients and SDKs know when to come back. Prefer it to 429, which says that this client exceeded its own quota, as in the rate-limiting lesson; a full queue is a statement about the service. Submit holds the mutex while it sends and records the job, so a worker cannot update a job that does not exist yet, and the close in Shutdown cannot race a send, which would panic. The counter IDs in the demo are for readability only. Real job IDs must be unguessable, and every GET must check that the caller owns the job, or /jobs/{n+1} hands one customer the report of another, as the tenant-isolation lesson warns.
Detach the request context, never the gin.Context
net/http cancels an incoming request's context when ServeHTTP returns, a moment after the 202 is written, so a job that runs on c.Request.Context() is canceled almost as soon as it starts. context.WithoutCancel returns a context that keeps the parent's values, such as the request ID, trace span and principal set by middleware, but has no deadline, never reports an error and has a nil Done channel. The worker adds the job's own budget with WithTimeout when the job starts rather than when it is enqueued, so time spent queued does not eat it. Give the worker the request's context and plain data, never *gin.Context or c.Copy(); the engine recycles context objects, as the context-workers lesson explains. gin.Recovery protects only the handler goroutine, and a panic in a worker goroutine kills the whole process, which is why execute recovers and records the job as failed. Shutdown here drains the queue and joins the workers. In production, bound that with the shutdown budget from the server-lifecycle lesson and give running jobs a pool-level stop signal; context.AfterFunc can cancel each job's context when the pool's context is canceled.
An in-memory pool is a model; durable jobs live in the database
Every queued and running job in this pool disappears on a deploy, a crash or an out-of-memory kill, and with two replicas the one that did not accept job 1 answers 404 for it. When losing a job is unacceptable, persist it before the 202: insert the job row in the same transaction as any business change it depends on, which is the outbox pattern from the systems.outbox-inbox lesson, and let workers claim due rows with a lease. A crashed worker's lease expires and another worker runs the job again, so execution becomes at least once and the work itself must be idempotent. A context cannot be stored, so persist the values the job needs, such as the trace ID and the principal, as columns. A client that retries a POST whose 202 was lost would create a second job, so accept an Idempotency-Key as the idempotency-keys lesson describes, and delete finished jobs and their results after a published retention period.
// A worker claims one due job. SKIP LOCKED lets many workers poll one table.
const claim = `
UPDATE jobs SET status = 'running', attempts = attempts + 1,
lease_until = now() + interval '5 minutes'
WHERE id = (
SELECT id FROM jobs
WHERE status = 'queued' OR (status = 'running' AND lease_until < now())
ORDER BY created_at
LIMIT 1
FOR UPDATE SKIP LOCKED)
RETURNING id, kind, input, trace_id`
var id, kind, traceID string
var input []byte
err := db.QueryRowContext(ctx, claim).Scan(&id, &kind, &input, &traceID)
if errors.Is(err, sql.ErrNoRows) {
return nil // nothing due: wait for a notification or the next poll tick
}This fragment runs against PostgreSQL in your own environment. The inner SELECT finds the oldest job that is queued or whose lease has expired, and FOR UPDATE SKIP LOCKED lets many workers run the same statement without blocking each other or claiming the same row. The UPDATE marks it running with a five-minute lease and counts the attempt, and the trace ID comes back as data because no context survived the restart. sql.ErrNoRows means nothing is due. A job that exceeds a maximum attempt count should move to failed rather than retry forever.
Test the lifecycle with channels, not sleeps
A test that sleeps and hopes a worker has started is slow on a fast machine and flaky on a loaded one. Make the work function observable instead: an unbuffered started channel proves that a worker holds a job, a release channel decides when it finishes, and Shutdown joins the workers before the final assertions. Cover the full queue and its Retry-After, validation failures that create no job, an unknown or foreign job ID, a job that returns an error, a job that panics, Submit during shutdown and a request context canceled before the worker starts. For deadlines, the synctest lesson shows how to test them without the wall clock. Run the suite with -race, because handlers and workers touch the pool at the same time. On the client side, poll with backoff and honor Retry-After, or let the client register a webhook that is called when the job reaches a terminal state; the webhook-receiver lesson covers the receiving end.
TAKE THIS WITH YOU
Validate synchronously, enqueue without blocking, answer 202 with a Location for the job, refuse a full queue with 503 and Retry-After, run each job on context.WithoutCancel plus its own deadline, and persist jobs when losing one is unacceptable.
Check your understanding
A Gin handler enqueues a job that carries c.Request.Context() and returns 202. What happens to that context by the time a worker runs the job?
Go to the source
Progress stays in this browser. No account needed.