py_semaphore (erlang_python v3.0.0)

View Source

ETS-based counting semaphore for rate limiting Python operations.

Based on the Discord semaphore pattern. Uses atomic ETS operations for high concurrency without a gen_server bottleneck.

The semaphore limits concurrent Python operations to prevent: - Memory exhaustion from unbounded request queuing - Dirty scheduler pool starvation - System overload under burst traffic

Summary

Functions

Acquire a slot in the semaphore. Blocks with exponential backoff until a slot is available or timeout. Returns ok on success, {error, max_concurrent} on timeout.

Get the current number of operations in flight.

Initialize the semaphore ETS table. Safe to call multiple times - will not recreate if already exists.

Get the maximum concurrent operations allowed.

Release a slot in the semaphore. Must be called after acquire/1 completes, typically in an after clause.

Dynamically set the maximum concurrent operations. Takes effect immediately for new acquire calls.

Functions

acquire(Timeout)

-spec acquire(timeout()) -> ok | {error, max_concurrent}.

Acquire a slot in the semaphore. Blocks with exponential backoff until a slot is available or timeout. Returns ok on success, {error, max_concurrent} on timeout.

current()

-spec current() -> non_neg_integer().

Get the current number of operations in flight.

init()

-spec init() -> ok.

Initialize the semaphore ETS table. Safe to call multiple times - will not recreate if already exists.

max_concurrent()

-spec max_concurrent() -> pos_integer().

Get the maximum concurrent operations allowed.

release()

-spec release() -> ok.

Release a slot in the semaphore. Must be called after acquire/1 completes, typically in an after clause.

set_max_concurrent(Max)

-spec set_max_concurrent(pos_integer()) -> ok.

Dynamically set the maximum concurrent operations. Takes effect immediately for new acquire calls.