> For the complete documentation index, see [llms.txt](https://docs.cennso.com/components/smc/3.15/llms.txt) (all documentation: [llms.txt](https://docs.cennso.com/llms.txt)). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cennso.com/components/smc/3.15/reference/load-control.md).

# Adaptive load control — technical reference

This page covers the internals of the adaptive load control subsystem in enough depth to reason about its runtime behavior on a production gateway. It is intended for operators who need to tune the controller, predict how it will respond to a given traffic shape, or correlate its state with incident symptoms.

For the operator-facing overview and configuration guide, see [Adaptive load control](https://docs.cennso.com/components/smc/3.15/config/load-control.md). For Prometheus metric definitions and key monitoring signals, see [Adaptive load control metrics](https://docs.cennso.com/components/smc/3.15/observability/metrics.md#adaptive-load-control-metrics). For the bundled Grafana dashboards, see [Adaptive load control dashboard](https://docs.cennso.com/components/smc/3.15/observability/dashboard-ergw-load-control.md) and [API latency dashboard](https://docs.cennso.com/components/smc/3.15/observability/dashboard-api-latency.md). For symptom-based diagnosis, see [Troubleshooting](https://docs.cennso.com/components/smc/3.15/troubleshooting/load-control.md).

## Architecture

The runtime flow for a single GTP request, under `adaptive` mode, is:

![Admission flow for a single GTP request in adaptive mode](https://docs.cennso.com/api/assets/components/smc/3.15/assets/load-control-flow.svg)

Five cooperating components:

1. **Dispatcher**. Routes each request to the `adaptive` path or to the rate-limit `jobs` path. Returns an opaque handle tagged with the chosen backend, so that completion always routes to the correct component even if the mode changes between admission and completion.
2. **Rejector**. A fast in-memory priority check that sheds requests before they enter the queue. A velocity-form proportional-integral-derivative (PID) controller computes a rejection ratio every 500 milliseconds; an empirical percentile tracker converts the ratio into a concrete priority threshold that reflects the actual distribution of recent requests.
3. **Priority queue**. An ordered set that buffers admitted requests when all inflight slots are occupied. Requests are dequeued in priority order. A `max_queue` cap prevents runaway growth under sudden overload.
4. **Scheduler**. Enforces a hard limit on the number of concurrently processed requests. Every slot is tracked by an Erlang process monitor so that a handler crash frees the slot for the next waiter.
5. **Vegas auto-tuner**. Watches processing latency and dynamically adjusts the inflight limit using the Gradient2 algorithm. It measures only processing time, not queue wait time, so the signal reflects actual backend capacity.

The design draws from Uber's Cinnamon load shedder. The adaptations for SMC use a velocity-form PID (to avoid integral windup pathologies) and the Netflix Gradient2 variant of Vegas (to avoid fixed-baseline traps during warm-up).

## Priority model

Every GTP message is classified into one of four load classes. Each class is assigned a numeric **tier** where **lower numbers mean higher priority**.

| Tier | Load class | GTP message types | Rationale |
| --- | --- | --- | --- |
| 0 | `delete` | Delete Session Request, Delete PDP Context | Always let session teardown through so resources can be freed. |
| 1 | `other` | Modify Bearer, Update Bearer, and all other signalling for existing sessions | Session maintenance for existing subscribers should not be lost under overload. |
| 2 | `data` | G-PDU (user-plane data) | User-plane forwarding is important but can be shed before signalling. |
| 3 | `create` | Create Session Request, Create PDP Context | New sessions are shed first under load. This protects subscribers who are already connected. |

Under overload, `create` traffic is shed first. Session teardown (`delete`) is always allowed through. This prevents the pathological case of an overloaded gateway that cannot free resources because it is busy rejecting the teardown requests that would release them.

GTP Echo Requests are handled at the socket level before the request logic runs and are **not** subject to load control — they always pass.

### Cohorts

Within each tier, requests are divided into 128 **cohorts** by hashing the GTP sequence number. GTP sequence numbers are 24-bit per-peer counters that increment by one on every request, so the hash distributes uniformly across all 128 cohorts even when all traffic originates from a single peer.

Cohorts make shedding *consistent*: a peer whose traffic happens to land in the shedded cohort range sees its requests rejected systematically rather than at random. This gives the peer a clear signal to back off, instead of a misleading mix of successes and failures.

### Admission priority and threshold

The full admission priority of a request is:

```text
priority = tier * 128 + cohort
```

This yields 512 distinct priority levels, with `0` as the highest priority (a `delete` in cohort 0) and `511` as the lowest (a `create` in cohort 127).

The **threshold** is an integer between 0 and 512. A request with `priority < threshold` is admitted; otherwise it is shed. Threshold `512` admits everything, threshold `0` rejects everything.

The PID controller does **not** choose the threshold directly. Instead, it produces a rejection ratio in the range `[0, 1]`, which is converted to a threshold through the empirical percentile tracker described below.

## PID controller (rejector)

The rejector runs a **velocity-form PID** controller. Velocity-form means the controller produces a *delta* to apply to the previous rejection ratio, rather than computing a fresh ratio from an accumulated integral. This avoids the "drain to zero" pathology that a windowed integrator exhibits at steady state.

The controller ticks every 500 milliseconds by default. Each tick, it recomputes the rejection ratio from observed counters and updates the admission threshold.

### Error signal

On each tick, the controller computes:

```text
InTotal       = requests admitted since the last tick
TotalArrivals = requests that reached the admission gate (admitted + shed)
OutTotal      = requests completed since the last tick
Inflight      = currently processing requests
FreeInflight  = max(0, inflight_limit - Inflight)
Capacity      = OutTotal + FreeInflight

Denom = max(TotalArrivals, Capacity)

        InTotal - Capacity
Error = ------------------      (when Denom = 0, Error = 0)
              Denom
```

The numerator `InTotal - Capacity` is the feedback-sensitive term. As the rejection ratio rises, `InTotal` falls, driving the error toward zero. Using `TotalArrivals` in the denominator bounds the signal to the range `[-1, 1]` and keeps it defined even when the gate is closed (`InTotal = 0`). When the gate is closed, the error becomes `-Capacity / TotalArrivals`, a small negative value that gradually drains the rejection ratio back down as capacity frees up.

At steady state (`InTotal ≈ Capacity`), the error is zero and the controller holds the rejection ratio constant.

### Velocity-form PID terms

```text
DeltaP = Kp * (Error - PrevError)                       (respond to change in error)
DeltaI = Ki * Error * dt                                (per-tick integral bump)
DeltaD = Kd * (Error - 2*PrevError + PrevPrevError) / dt (second-difference damping)
DeltaR = DeltaP + DeltaI + DeltaD

rejection_ratio = clamp(PrevRejection + DeltaR, 0.0, 1.0)
```

When `Error = 0` is sustained, all three deltas are zero, so `rejection_ratio` holds at its current value. The accumulated control authority lives in the `rejection_ratio` itself; there is no integral window to drain. Integral windup is prevented by the output clamp: a clamped delta cannot drive the rejection ratio below 0 or above 1.

### Threshold via empirical percentile

Rather than mapping the rejection ratio to a threshold with a fixed formula, the rejector uses the empirical percentile tracker ([described below](#empirical-percentile-tracker)):

```text
AdmitPct  = (1 - rejection_ratio) * 100
threshold = percentile(AdmitPct, recent_priority_distribution)
```

`percentile(N, tracker)` returns the smallest priority `T` such that at least `N` per cent of recently observed requests have priority `< T`. Setting `threshold = T` therefore admits exactly the lowest-priority fraction `(1 - rejection_ratio)` of actual traffic, regardless of how skewed the tier and cohort distribution happens to be.

### Parameters

| Parameter | Default | Description |
| --- | --- | --- |
| `loadControl.rejector.tick_interval` | `500` | Controller tick interval in milliseconds. |
| `loadControl.rejector.kp` | `0.1` | Proportional gain. Reacts to changes in the error signal between ticks. |
| `loadControl.rejector.ki` | `1.4` | Integral gain. Dominates the steady-state response. The design guide recommends `0.2`; the schema default of `1.4` is kept for upstream compatibility but is generally too aggressive for SMC traffic patterns. |
| `loadControl.rejector.kd` | `0.05` | Derivative gain. A second-difference of the error signal. Dampens oscillation but amplifies high-frequency noise. |
| `loadControl.rejector.priority_window_size` | `1000` | Size of the sliding window over admitted requests used to compute the priority distribution. |

### Tuning guidance

`ki` dominates steady-state behavior. A rough sizing rule: at the largest typical error (`|Error|` around 0.5 to 1.0), `Ki * Error * dt` should move the rejection ratio by a small fraction per tick, 5 to 10 per cent, so that convergence happens over 5 to 10 ticks rather than in a single tick. With `dt = 0.5 s`:

- `Ki = 0.2` gives `DeltaI ≈ 0.05` per tick at `Error = 0.5` — stable convergence.
- `Ki = 1.0` gives `DeltaI ≈ 0.25` per tick — usually too aggressive. The rejection ratio saturates in a single tick and bang-bangs between zero and one.

The schema default of `Ki = 1.4` is taken verbatim from upstream material. It is too large for the bounded error signal SMC uses (`(InTotal - Capacity) / max(TotalArrivals, Capacity)`). For most deployments, set `Ki = 0.2` explicitly.

`kp` reacts to error *changes*, not absolute magnitude. Keep it small (`≤ 0.1`). Larger values amplify noise from per-tick counter jitter.

`kd` adds a second-difference term that can damp oscillation but amplifies high-frequency noise. Small values (`≤ 0.05`) or zero are safest. If the structured log shows `delta_d` swings comparable in magnitude to `delta_i`, reduce `kd`.

`priority_window_size = 1000` corresponds to roughly eight seconds of history at 120 requests per second. Shorter windows track changes in the traffic mix faster; longer windows produce smoother thresholds.

## Empirical percentile tracker

The empirical percentile tracker is a pure-functional Fenwick tree (binary indexed tree) plus a sliding-window queue. It tracks the priorities of the last `priority_window_size` admitted requests and answers the question "what is the priority value at percentile `P`?" in logarithmic time in the maximum priority value (512), which matters because every controller tick recomputes the threshold.

### Why it matters

Consider a deployment where 90 per cent of traffic is `create` (priorities 384 to 511) and 10 per cent is `delete` (priorities 0 to 127). A linear map from rejection ratio to threshold, for example `threshold = 512 - rejection_ratio * 512`, misbehaves. At `rejection_ratio = 0.5`, it would set `threshold = 256`, which sheds 100 per cent of creates and 0 per cent of deletes — effectively 90 per cent shed overall, not 50 per cent.

The percentile tracker returns the priority at which the 50 per cent mark of recent traffic actually falls. For the 90/10 distribution above, that lands inside the create band and sheds exactly half of the creates, which is the intended 50 per cent rejection.

This makes the controller's behavior predictable for the operator: setting `rejection_ratio = 0.3` sheds the lowest-priority 30 per cent of actual traffic, whatever shape that traffic currently has.

## Priority queue

The queue is an ordered set of pending requests, dequeued in priority order whenever a slot becomes available.

### Queue ordering

Two ordering modes are supported, selected by `loadControl.queue.mode`:

#### `strict` (default)

Queue key: `{priority, timestamp, sequence}`.

Requests are dequeued in strict priority order. Within the same priority level, ordering is first-in-first-out by timestamp. A monotonic sequence counter breaks ties when two requests arrive in the same microsecond.

Strict mode maximizes priority fairness: the highest-priority waiting request is always served next. The downside is that during sustained overload, the lowest-priority tier can starve indefinitely.

#### `aging`

Queue key: `{priority * scale + timestamp, sequence}`.

A single effective value combines priority and arrival time. Older requests naturally drift toward smaller effective values (higher priority) as newer arrivals get larger timestamps.

An old request at priority `P_low` overtakes a fresh request at priority `P_high` after:

```text
delta > (P_low - P_high) * scale  microseconds
```

With `scale = 1000000` (one second per priority unit):

| Old request | New request | Crossover time |
| --- | --- | --- |
| priority 300 (`create`) | priority 0 (`delete`) | 300 seconds |
| priority 200 (`data`) | priority 100 (`other`) | 100 seconds |
| priority 300 (`create`) | priority 200 (`data`) | 100 seconds |

The `scale` parameter controls the aging balance:

- `scale = 0` is pure first-in-first-out (no priority effect).
- `scale` very large is effectively strict priority (aging never catches up within a reasonable timeout).

Aging mode prevents complete starvation of low-priority traffic during sustained overload. For fairness-sensitive deployments, pair `mode: aging` with a `scale` chosen such that a create request waiting close to `max_wait` milliseconds is guaranteed to be served before it times out.

### Queue parameters

| Parameter | Default | Description |
| --- | --- | --- |
| `loadControl.queue.mode` | `strict` | Ordering mode: `strict` or `aging`. |
| `loadControl.queue.scale` | `1000000` | Aging-mode scale factor in microseconds per priority unit. |
| `loadControl.queue.max_inflight` | `100` | Maximum concurrent requests. The Vegas auto-tuner tunes the runtime limit within `[min_inflight, max_inflight]`. |
| `loadControl.queue.max_wait` | `5000` | Maximum queue wait time in milliseconds. Requests waiting longer are rejected with a timeout error. |
| `loadControl.queue.max_queue` | `0` | Maximum queue depth. Requests beyond this are rejected immediately. `0` means unlimited. |

The `max_queue` cap is a second line of defense against sudden overload. When the PID controller has not yet caught up — for example, while the integral term is still unwinding after an idle period — admitted requests that exceed processing capacity accumulate as queue waiters, each holding a process monitor, a timer, and a queue entry. `max_queue` bounds the memory cost of this transient buildup. The PID handles steady-state shedding; `max_queue` handles the millisecond-scale transient.

> [!TIP]
> For deployments that run close to capacity, set `max_queue` to roughly `2 * max_inflight`. This gives the PID controller a few ticks of headroom to react to a burst without the queue growing without bound.

## Scheduler (inflight limit)

The scheduler enforces a hard limit on the number of requests being processed simultaneously.

- When `inflight < max_inflight`, the request is granted a slot immediately.
- When `inflight >= max_inflight`, the request is inserted into the priority queue. The caller blocks until a slot becomes available or `max_wait` expires.
- When a request completes, the scheduler pops the highest-priority waiter and grants it the freed slot.

All callers are monitored. If a process crashes while processing a request, its slot is reclaimed and the next waiter is dequeued. If a process crashes while queued, it is removed from the queue. Crashes cannot leak slots.

The `max_inflight` value is the **upper bound** on concurrency. The Vegas auto-tuner continuously adjusts the runtime limit within `[min_inflight, max_inflight]`. In most deployments, the runtime limit stabilizes well below `max_inflight` when latency is the binding constraint, and grows toward `max_inflight` when latency is flat and arrival rate is high.

## Vegas auto-tuner

The Vegas auto-tuner dynamically adjusts the concurrency limit (`max_inflight`) based on observed request processing latency. The algorithm is a SMC-specific adaptation of TCP Vegas, using the Netflix Gradient2 variant of dual-window latency comparison.

### How it works

1. **Latency collection.** Every completed request reports its processing duration (from slot grant to completion). Samples are stored in a reservoir sample of bounded size (1,000 entries, Algorithm R) so that memory is bounded even under sustained high traffic.
2. **Tick.** At each sampling interval (adaptive, between `min_interval` and `max_interval` milliseconds), the 90th percentile (P90) latency is computed from the reservoir and smoothed with an exponential moving average (EMA). If the reservoir contains fewer than `min_samples` entries, the tick is a no-op. The interval to the next tick is computed continuously from the just-observed sample rate as the time expected to accumulate `min_samples` more samples, clamped into `[min_interval, max_interval]`. High traffic therefore drives the interval down toward `min_interval`, low traffic up toward `max_interval`, and a cold start defers to `max_interval` until the first window provides a rate estimate.
3. **Dual-window gradient (Gradient2).** Instead of comparing latency against a fixed baseline — which can get stuck at an artefact from the warm-up period — Vegas computes the **ratio** of a slow-moving long-term EMA to a fast-moving current EMA. Both windows adapt naturally, so there is no fixed baseline. The long-term EMA uses exponential decay (with `long_ema_alpha`) so it adapts to genuine long-term latency changes while filtering transient spikes.
4. **Covariance check.** Over a sliding window of 50 intervals, Vegas computes the covariance of `(actual_concurrency, throughput)` using Little's Law (`throughput = concurrency / latency`). A negative covariance means more concurrency is actually reducing throughput, which indicates the system is overloaded regardless of absolute latency.
5. **Adjustment.** The new limit is computed as:
   ```text
   gradient  = clamp(long_term_p90 / current_p90, min_gradient, 1.0)
   raw_limit = gradient * current_limit + sqrt(current_limit)
   new_limit = current_limit * (1 - smoothing) + raw_limit * smoothing
   ```
- `gradient ≈ 1.0` means latency is stable. The limit grows by roughly `sqrt(limit) * smoothing` per tick (additive increase).
- `gradient < 1.0` means the current P90 latency exceeds the long-term baseline. The limit shrinks proportionally (multiplicative decrease).
- `gradient = min_gradient` (`0.5` by default) is the floor. A single spike cannot halve the limit in one tick.
- **Covariance override.** If covariance is negative, Vegas forces a multiplicative decrease (`new_limit = limit - max(1, floor(limit * 0.1))`) regardless of the gradient.
6. **Bounds.** The new limit is clamped to `[min_inflight, inflight_limit]`.

### Latency measurement

Vegas measures **processing time** only — from the moment the inflight slot is granted until the handler reports completion. Queue wait time is excluded. This gives Vegas a clean signal about actual backend latency, not contaminated by queue delays. If Vegas measured queue-plus-processing time, it would feed back on itself: a growing queue would increase measured latency, causing Vegas to lower the limit, causing the queue to grow further.

### Parameters

| Parameter | Default | Description |
| --- | --- | --- |
| `loadControl.vegas.min_interval` | `2000` | Minimum sampling interval in milliseconds. |
| `loadControl.vegas.max_interval` | `30000` | Maximum sampling interval in milliseconds. |
| `loadControl.vegas.min_samples` | `250` | Minimum number of latency samples before adjusting. |
| `loadControl.vegas.inflight_limit` | `100` | Upper bound on the inflight limit (same as `queue.max_inflight`). |
| `loadControl.vegas.min_inflight` | `0` | Lower bound on the inflight limit. `0` means "number of Erlang schedulers", typically the number of CPU cores. |
| `loadControl.vegas.ema_alpha` | `0.25` | EMA smoothing factor for the short-term P90 signal. Lower values produce a smoother, slower-reacting signal. |
| `loadControl.vegas.long_ema_alpha` | `0.01` | EMA smoothing factor for the long-term latency baseline. Must be much smaller than `ema_alpha` so the two windows separate. |
| `loadControl.vegas.smoothing` | `1.0` | Limit change smoothing factor. Lower values produce smoother limit transitions; higher values respond faster. |
| `loadControl.vegas.min_gradient` | `0.01` | Floor on the gradient ratio. Prevents a single latency spike from dropping the limit drastically. |

### Tuning guidance

`min_samples` prevents premature adjustments during low-traffic periods. Keep it at least 100. For deployments with sparse load, raise it to 500 to avoid acting on sampling noise.

`ema_alpha = 0.25` gives a smoothing window of roughly four ticks. Reduce it for a smoother signal (slower reaction); increase it to react faster. At the extreme, `ema_alpha = 1.0` disables smoothing entirely.

`long_ema_alpha = 0.01` gives a smoothing window of roughly 100 ticks — the long-term latency reference. Reduce it for a more stable (slower) baseline; increase it to make the baseline more responsive. The ratio of `ema_alpha / long_ema_alpha` determines how sensitive Vegas is to medium-frequency latency changes.

`smoothing` dampens limit changes. `smoothing = 1.0` applies the raw computed limit directly; lower values blend the new limit with the previous one. For deployments that tolerate limit oscillations, set `smoothing = 1.0`. For deployments where stable concurrency is a priority, set `smoothing = 0.2`.

`min_gradient = 0.01` means a single latency spike can drop the limit by 99 per cent. That is aggressive. For stability, set `min_gradient = 0.5`, which caps the single-tick decrease at 50 per cent. The design guide recommends `0.5` for most deployments; the schema default of `0.01` is preserved for upstream compatibility.

## Configuration reference skeleton

For the complete list of Helm values with types, defaults, and short descriptions, see the [chart configuration reference](https://docs.cennso.com/components/smc/3.15/installation/chart-configuration.generated.md). The table below summarises the structure.

```yaml
loadControl:
  mode:                       # adaptive | rate-limit | rate-limit-observe
  rateLimit:                  # rate-limit mode only
    create: { rate, counter, max_time, cpu_feedback }
    delete: { rate, counter, max_time, cpu_feedback }
    data:   { rate, counter, max_time, cpu_feedback }
    other:  { rate, counter, max_time, cpu_feedback }
  queue:                      # adaptive mode only
    mode:                     # strict | aging
    scale:
    max_inflight:
    max_wait:
    max_queue:
  rejector:                   # adaptive mode only
    tick_interval:
    kp:
    ki:
    kd:
    priority_window_size:
  vegas:                      # adaptive mode only
    min_interval:
    max_interval:
    min_samples:
    inflight_limit:
    min_inflight:
    ema_alpha:
    long_ema_alpha:
    smoothing:
    min_gradient:
```

The chart emits a `load_control` section in the generated configuration only when at least one sub-key is set. An empty `loadControl: {}` (the default) is equivalent to omitting the section entirely, and SMC runs in rate-limit mode.

## Read more

- [Adaptive load control](https://docs.cennso.com/components/smc/3.15/config/load-control.md) — operator overview, mode selection guidance, and migration path.
- [Adaptive load control metrics](https://docs.cennso.com/components/smc/3.15/observability/metrics.md#adaptive-load-control-metrics) — Prometheus metric reference and key monitoring signals.
- [Adaptive load control dashboard](https://docs.cennso.com/components/smc/3.15/observability/dashboard-ergw-load-control.md), [API latency dashboard](https://docs.cennso.com/components/smc/3.15/observability/dashboard-api-latency.md) — bundled Grafana dashboards.
- [Troubleshooting](https://docs.cennso.com/components/smc/3.15/troubleshooting/load-control.md) — symptom-based diagnosis for the rejector, Vegas, and shadow-mode comparisons.
