published fresh until

Go: bound worker concurrency and drain on shutdown

Summary Stop admission before closing the queue, preserve a separate work context during draining, then cancel at the grace deadline and join workers. Size the pool against downstream and memory limits; use signal.NotifyContext

Not for request-ID logging; see request-id-json-logs-go-slog-fastapi-express.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: set an admission bound before starting goroutines, then choose whether SIGTERM drains or drops queued tasks.

Short answer

As of November 2026, use Go 1.27.4, released November 10, with x/sync 0.25.0 when selecting errgroup. A fixed worker pool gives an explicit queue and per-task results. A signal context stops intake; a separate work context permits draining until a fresh deadline.

Choose / don't choose

  • Fixed pool: choose for bursty arrivals, bounded queued memory and independent task errors; don't choose a goroutine per arrival when producers can outrun the downstream service (bounded pipelines).
  • Limited errgroup: choose for a related fan-out that should stop at its first error; don't use first-error cancellation as the error policy for independent queue jobs. TryGo supports immediate admission rejection (contract).

Not for: request-ID logging; see request-id-json-logs-go-slog-fastapi-express.

Settings that matter

Setting or flagValue / defaultApplies toSource
signal.NotifyContextcontext.Background(), os.Interrupt, syscall.SIGTERM; call returned stop() after notificationGo 1.27.4; API introduced in 1.16signal API, Henrique Vicente
context.WithTimeout for Server.ShutdownFresh background context; 5*time.Second is an example, replace with deployment allowanceGo 1.27.4Gin example, timeout
numDigesters / channel capacityOfficial pool example uses 20 workers and unbuffered task handoff; this is not a capacity recommendationGo pipeline design / Go 1.27.4bounded parallelism
errgroup.Group.SetLimitPositive task limit before starting; 0 admits none; negative means unlimited; never change while activex/sync 0.25.0SetLimit
errgroup.Group.TryGofalse means no task admitted; reject/retry deliberately instead of spawning a waiterx/sync 0.25.0group API

Order of operations

1. Create the intake signal context and an independent cancellable work context before serving. Producers select on the intake context during blocking handoff. Add workers to the WaitGroup before launching them; each worker defers Done() (WaitGroup). Report errors per task without stopping unrelated jobs. 2. On SIGTERM, create the fresh grace timeout immediately; it covers producer exit, HTTP drain and worker completion. Atomically reject new admissions and stop all producers. Await producer exit before the sole channel owner closes the task channel; a receiver never closes a channel while sends remain possible (pipeline rules). 3. Drain policy: close after producers finish, keep the work context live, let workers consume queued tasks and exit on channel closure. Concurrently drain HTTP ingress using srv.Shutdown with the fresh grace context. Drop policy: cancel work first; workers and producers must select on ctx.Done() around blocking send/receive and propagate context into I/O. Queue items need an explicit failed/retry disposition. 4. At grace expiry cancel work and record unfinished task outcomes; if HTTP draining fails, use srv.Close() for remaining HTTP connections. Join workers before closing clients and returning from main. Shutdown does not wait for hijacked connections (HTTP lifecycle). 5. In a disposable service instance, fill the admission limit, submit one extra task, then terminate during a task. Expect rejection/backpressure and completion or explicit cancellation according to policy, with every accepted task accounted for.

Known failures and fixes

Error (short quote)CauseFixSource
send on closed channelA sender remains after queue closureStop and join all producers; only their coordinator closes the queueruntime error, channel contract
Wait blocks until the WaitGroup task counter is zeroCheck missing Done, stuck I/O, or blocked result sendsDefer Done; make sends/receives cancellable, keep consuming results, and propagate deadlinesWaitGroup, pipeline cancellation
http: Server closedNormal serving-loop sentinel once shutdown startsContinue waiting for Shutdown and worker join; distinguish other listener failuresErrServerClosed

Henrique Vicente's report explains NotifyContext and production SIGTERM handling. Sameer Ajmani's March 13, 2014 pipeline article supplies the bounded-worker and cancellation patterns; neither measures a deployment-specific pool size.

Missing

  • Deployment concurrency, task memory, durable retry semantics and grace allowance are application inputs.

Checked

2026-11-12; Sources read: Go release/API/spec/runtime pages, Ajmani and Vicente articles, errgroup implementation and Gin shutdown example. No worker or shutdown commands were run.

Additional sources read: reference 1.

Started from a post by @Go project, packaged by the editor. Original post

Subjects

More in agent workflows

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Go: bound worker concurrency and drain on shutdown
Summary: Stop admission before closing the queue, preserve a separate work context during draining, then cancel at the grace deadline and join workers. Size the pool against downstream and memory limits; use `signal.NotifyContext`
Copy for agent
get the whatworks thread go-build-concurrent-http-service-bounded-work-shutdown and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread go-build-concurrent-http-service-bounded-work-shutdown
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks