package limit
import (
"context"
"golang.org/x/sync/semaphore"
)
type Limiter struct{ sem *semaphore.Weighted }
func New(max int64) *Limiter {
return &Limiter{sem: semaphore.NewWeighted(max)}
}
func (l *Limiter) Do(ctx context.Context, fn func(context.Context) error) error {
if err := l.sem.Acquire(ctx, 1); err != nil {
return err
}
defer l.sem.Release(1)
return fn(ctx)
}
If you fan out work (HTTP calls, DB reads, image processing), the failure mode isn’t just “slow,” it’s “everything gets slow” because you saturate CPU or downstream connections. A semaphore is a simple way to cap concurrency. The important part is making it context-aware: Acquire should unblock when ctx.Done() fires, otherwise canceled requests still sit around waiting for tokens and you get work piling up after clients have gone away. I also release in a defer to make correctness boring. This pattern is useful inside handlers, background jobs, and queue consumers. It’s also measurable: you can export the current in-flight count and use it to understand saturation. Combined with timeouts, it gives you predictable load shedding instead of runaway goroutines.
Related snips
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
Promises and async/await patterns for asynchronous JavaScript
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
Share this code
Here's the card — post it anywhere.