Electric.AdmissionControl (electric v1.2.4)

View Source

Simple admission control using ETS-based counters to limit concurrent requests per stack.

This module prevents server overload by:

  • Limiting the number of concurrent requests per type of request (initial or existing) within a stack
  • Failing fast with 503 + Retry-After when at capacity
  • Using cheap ETS operations for minimal overhead

Usage

# Try to acquire a permit for a stack
case Electric.AdmissionControl.try_acquire(stack_id, :initial, max_concurrent: 1000) do
  :ok ->
    # Request is allowed, process it
    # Don't forget to call release/1 when done!

  {:error, :overloaded} ->
    # Too many concurrent requests, return 503
end

# Always release the permit when done
Electric.AdmissionControl.release(stack_id, :initial)

Configuration

The max_concurrent limit can be configured in your config files:

config :electric, :max_concurrent_requests, %{initial: 300, existing: 1000}

Summary

Functions

Returns a specification to start this module under a supervisor.

Get the current number of in-flight requests for a stack.

Release a permit for the given stack_id.

Start the admission control GenServer.

Try to acquire a permit for the given stack_id.

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

get_current(stack_id, opts \\ [])

Get the current number of in-flight requests for a stack.

Returns a map with :initial and :existing counts.

Useful for monitoring and debugging.

Options

  • :table_name - ETS table name (default: :electric_admission_control)

Examples

iex> Electric.AdmissionControl.get_current("stack-123")
%{initial: 5, existing: 10}

release(stack_id, kind, opts \\ [])

Release a permit for the given stack_id.

Always call this after processing a request, even if it errors. Consider using a try/after or Plug's register_before_send/2 callback.

Options

  • :table_name - ETS table name (default: :electric_admission_control)

Examples

iex> Electric.AdmissionControl.release("stack-123", :initial)
:ok

start_link(opts)

Start the admission control GenServer.

Options

  • :table_name - Custom ETS table name (default: :electric_admission_control)
  • :name - GenServer name (default: __MODULE__)

try_acquire(stack_id, kind, opts \\ [])

Try to acquire a permit for the given stack_id.

Returns :ok if permit granted, {:error, :overloaded} if at capacity.

Options

  • :max_concurrent - Maximum concurrent requests allowed (default: 1000)
  • :table_name - ETS table name (default: :electric_admission_control)

Examples

iex> Electric.AdmissionControl.try_acquire("stack-123", :initial, max_concurrent: 1000)
:ok

iex> Electric.AdmissionControl.try_acquire("stack-123", :initial, max_concurrent: 1)
{:error, :overloaded}