What Broke First When Building a Go Async Task Framework
Lessons from maintaining a Go async job runner across dozens of service releases: weighted concurrency limits, lease fencing against duplicate execution, and two-phase graceful draining.
Writing a worker pool in Go takes twenty lines of code: a buffered channel, a handful of goroutines, and a sync.WaitGroup. That simplicity is deceptive. The moment your jobs stop being 30-millisecond JSON transforms and become 3-minute media renders or third-party AI calls across rolling deployments, almost every naive assumption breaks at once.
Here are the three failure modes that hit us earliest in production, and the patterns that actually held up across dozens of service releases.
1. Fixed Worker Counts Do Not Fit Mixed-Cost Jobs
A fixed maxWorkers = 16 pool assumes every task consumes roughly the same resources. In practice, a single queue often carries wildly different workloads: a 200 ms metadata check, a 4K image crop that spikes 600 MB of RAM, and a 90-second video export that pins four CPU cores.
When 16 heavy jobs arrive together, the pod OOM-kills even though concurrency stayed "within limits." When 16 lightweight jobs arrive, the box sits at 8% CPU.
The fix was switching from a flat worker count to a weighted semaphore (golang.org/x/sync/semaphore) where each task declares an estimated cost before being admitted:
type Runner struct {
budget *semaphore.Weighted
}
func (r *Runner) Dispatch(ctx context.Context, task Task) error {
weight := task.ResourceWeight() // e.g. 1 for metadata, 4 for image, 8 for video
if err := r.budget.Acquire(ctx, weight); err != nil {
return err
}
go func() {
defer r.budget.Release(weight)
r.execute(ctx, task)
}()
return nil
}Just as important: pull from the broker only after acquiring budget, not before. Pulling 100 messages into local memory and blocking them on a semaphore creates hidden lag, breaks broker-level fair dispatch across pods, and forces visibility timeouts to fire while jobs are still sitting untouched in RAM.
2. Long-Running Jobs Need Lease Renewal and Fencing Tokens
With a 30-second message visibility timeout, any job that takes two minutes will be redelivered to a second worker while the first worker is still halfway through. Increasing the static timeout to 10 minutes is a trap too: if a pod crashes after 5 seconds, the user waits 10 minutes before anyone retries it.
What works reliably is a short lease with background heartbeat renewal, paired with a monotonically increasing fencing token (attempt or lease_version) checked on every state transition:
func (w *Worker) runWithLease(parent context.Context, task Task) error {
ctx, cancel := context.WithCancel(parent)
defer cancel()
// Renew lease every 10s (lease TTL = 30s). If renewal fails, cancel execution
// immediately instead of continuing as a zombie worker.
go func() {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
ok, err := w.store.ExtendLease(ctx, task.ID, task.LeaseVersion, 30*time.Second)
if err != nil || !ok {
cancel()
return
}
}
}
}()
return w.handler.Handle(ctx, task)
}And at the storage boundary, every completion or checkpoint write asserts the token:
UPDATE async_tasks
SET status = 'succeeded', result = $1, updated_at = NOW()
WHERE id = $2
AND lease_version = $3
AND status = 'running';If Worker A pauses during a GC stall or network partition and Worker B legitimately takes over with lease_version = 2, Worker A's stale commit matches zero rows instead of clobbering Worker B's newer state.
3. Two-Phase Graceful Draining on Rolling Releases
Most Kubernetes services terminate cleanly in 5 seconds because HTTP requests finish in milliseconds. Async workers running 2-minute tasks get SIGTERM during every rolling deploy, and if terminationGracePeriodSeconds is still at the default 30 seconds, Kubernetes sends SIGKILL straight through in-flight work.
Clean releases required splitting shutdown into two explicit phases:
SIGTERM received
├─ Phase 1 (immediate): flip readiness probe to 503, stop pulling new tasks
├─ Phase 2 (drain window): wait for in-flight tasks up to drainTimeout
└─ Phase 3 (fallback): cancel remaining contexts, release leases cleanly for immediate requeueNotice Phase 3: explicitly releasing the lease before exiting is much better than letting the process die and waiting for TTL expiration. Downstream users see a retry start in under a second instead of stalling for 30 seconds waiting for a dead pod's lease to time out.
In Kubernetes manifests, align the three timers so they do not fight each other:
| Timer | Example Value | Role |
|---|---|---|
App drainTimeout |
150s |
Wait for active tasks to finish naturally |
| Lease cleanup buffer | 15s |
Cancel remaining tasks and release leases back to DB |
terminationGracePeriodSeconds |
180s |
Must exceed drainTimeout + buffer so SIGKILL never hits early |
Observability Signals That Actually Caught Incidents
Once the runner was stable, four metrics caught almost every regression before users noticed:
- Queue wait time (
started_at - enqueued_at) by priority class — far more actionable than raw queue length. - Lease loss count — any non-zero spike immediately points to DB latency, GC pauses, or broken heartbeat loops.
- Retry amplification ratio (
attempts / unique_jobs) — exposes poison-pill payloads burning compute before hitting the dead-letter queue. - Forced requeues during deploy — tells you whether your
drainTimeoutstill covers your P95 task duration as workloads evolve.
None of these pieces require exotic frameworks. Most of the reliability comes from respecting the lifecycle boundaries: admit only what fits in memory, prove you still own the lease when writing results, and hand unfinished work back cleanly when a pod rotates out.