Weighted Semaphore Limiter

Bound concurrent work by cost using a weighted semaphore, admitting tasks only while capacity remains.

GoResilience

Code

gosnippet
49 lines
package limiter

import (
    "context"
    "errors"
    "sync"
)

var ErrExhausted = errors.New("capacity exhausted")

type Weighted struct {
    mu       sync.Mutex
    capacity int64
    inUse    int64
}

func New(capacity int64) *Weighted {
    return &Weighted{capacity: capacity}
}

func (w *Weighted) TryAcquire(weight int64) error {
    if weight <= 0 || weight > w.capacity {
        return ErrExhausted
    }
    w.mu.Lock()
    defer w.mu.Unlock()
    if w.inUse+weight > w.capacity {
        return ErrExhausted
    }
    w.inUse += weight
    return nil
}

func (w *Weighted) Release(weight int64) {
    w.mu.Lock()
    defer w.mu.Unlock()
    w.inUse -= weight
    if w.inUse < 0 {
        w.inUse = 0
    }
}

func (w *Weighted) WithContext(ctx context.Context, weight int64, fn func() error) error {
    if err := w.TryAcquire(weight); err != nil {
        return err
    }
    defer w.Release(weight)
    return fn()
}

Inside the snippet

Structurally, expect the functions New, TryAcquire, Release and WithContext and nothing else.

Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Watch out for

  • Errors are ordinary return values; skipping the err check means using a zero value silently.

Using it

The entry-point signature is func New(capacity int64) *Weighted

New is the public entry point; everything else in the file exists to support it.

Key statements

func (w *Weighted) WithContext(ctx context.Context, weight int64, fn func() error) error {
    if err := w.TryAcquire(weight); err != nil {
        return err
    }
    defer w.Release(weight)
    return fn()
}
func (w *Weighted) TryAcquire(weight int64) error {
    if weight <= 0 || weight > w.capacity {
        return ErrExhausted
    }
    w.mu.Lock()
    defer w.mu.Unlock()
    if w.inUse+weight > w.capacity {
        return ErrExhausted
    }
    w.inUse += weight
    return nil
}
func (w *Weighted) Release(weight int64) {
    w.mu.Lock()
    defer w.mu.Unlock()
    w.inUse -= weight
    if w.inUse < 0 {
        w.inUse = 0
    }
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
No exceptions — `error` returns checked at 1 site, and callers branch on `err` first.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `New`, `TryAcquire`, `Release` at load time.