# Class RateLimiter

Token bucket rate limiter implementation

- Defined in utils/rateLimiter.ts:79

##### Index

### Constructors

constructor

### Properties

intervalMs
lastRefill
tokens
tokensPerInterval

### Methods

getAvailableTokens
getMaxTokens
getStatus
refill
removeTokens
reset
tryRemoveTokens
resolveTimeout

## Constructors

### constructor

- new RateLimiter(options: RateLimiterOptions): RateLimiter

  #### Parameters

  - options: RateLimiterOptions

  #### Returns RateLimiter

  - Defined in utils/rateLimiter.ts:85

## Properties

### `Private` `Readonly` intervalMs

intervalMs: number

- Defined in utils/rateLimiter.ts:82

### `Private` lastRefill

lastRefill: number

- Defined in utils/rateLimiter.ts:83

### `Private` tokens

tokens: number

- Defined in utils/rateLimiter.ts:80

### `Private` `Readonly` tokensPerInterval

tokensPerInterval: number

- Defined in utils/rateLimiter.ts:81

## Methods

### getAvailableTokens

- getAvailableTokens(): number

  Returns the number of tokens currently available in the bucket.

  Triggers a refill calculation based on elapsed time before returning the value, so the result reflects the current real-time availability.

  #### Returns number

  Current token count (may be fractional; floor before display)

  #### Example

      const tokens = rateLimiter.getAvailableTokens();
      console.log(`${tokens} / ${rateLimiter.getMaxTokens()} tokens available`);

  #### Since

  0.8.0

  - Defined in utils/rateLimiter.ts:291

### getMaxTokens

- getMaxTokens(): number

  Returns the maximum token capacity of this bucket.

  Equal to the `tokensPerInterval` value passed at construction time. Does not trigger a refill calculation.

  #### Returns number

  Maximum number of tokens the bucket can hold

  #### Example

      const max = rateLimiter.getMaxTokens(); // e.g. 100

  #### Since

  0.8.0

  - Defined in utils/rateLimiter.ts:311

### getStatus

- getStatus(): RateLimiterStatus

  Returns a typed status snapshot for health checks and monitoring.

  Triggers a refill calculation so the snapshot reflects real-time bucket state. Useful for `/health` endpoints and Prometheus exporters.

  #### Returns RateLimiterStatus

  Current RateLimiterStatus snapshot with `availableTokens`, `maxTokens`, and `utilizationPercent` (0–100)

  #### Example

      const status = rateLimiter.getStatus();
      console.log(`${status.utilizationPercent}% utilized`);
      // e.g. "45% utilized"

  #### Since

  0.8.0

  - Defined in utils/rateLimiter.ts:333

### `Private` refill

- refill(): void

  Refill tokens based on elapsed time

  #### Returns void

  - Defined in utils/rateLimiter.ts:132

### removeTokens

- removeTokens(
  count: number,
  options?: { timeoutMs?: number },
  ): Promise<RateLimitResult>

  Attempts to consume `count` tokens from the bucket, waiting asynchronously until tokens are available or the timeout expires.

  Refills the bucket based on elapsed time before each check. If sufficient tokens are available they are consumed immediately. Otherwise the method sleeps until the bucket has enough tokens and retries. If the required wait would exceed `options.timeoutMs` (default 5000 ms) the call returns immediately with `allowed: false` and a `retryAfterMs` hint. The timeout is enforced as a hard deadline: even if a sleep fires slightly late due to event-loop delay, tokens are never consumed after the deadline has elapsed.

  #### Parameters

  - count: number

    Number of tokens to consume (must be a finite integer ≥ 1 and ≤ `tokensPerInterval`); throws for invalid values

  - `Optional` options: { timeoutMs?: number }

    - ##### `Optional` timeoutMs?: number

      Maximum time to wait in milliseconds (default 5000); non-finite or negative values are coerced to `0`, meaning the call never blocks and returns `allowed: false` immediately if tokens are unavailable

  #### Returns Promise<RateLimitResult>

  Promise resolving to a RateLimitResult. `allowed` is `true` when tokens were consumed, `false` when the timeout was reached. `remainingTokens` is always a non-negative integer (`Math.floor` of the internal fractional bucket state); it may differ from RateLimiter.getAvailableTokens which returns the raw fractional value.

  #### Example

      const result = await rateLimiter.removeTokens(1);
      if (!result.allowed) {
        console.warn(`Rate limited – retry after ${result.retryAfterMs}ms`);
      } else {
        const data = await fetchFromEPAPI('/meps');
      }

  #### Security

  Prevents abusive high-frequency requests to the EP API. Per ISMS Policy AC-003, rate limiting is a mandatory access control.

  #### Since

  0.8.0

  - Defined in utils/rateLimiter.ts:180

### reset

- reset(): void

  Resets the bucket to full capacity and clears the refill timer.

  Useful in tests or after a planned maintenance window where queued demand should not be penalised by an already-depleted bucket.

  #### Returns void

  #### Example

      afterEach(() => {
        rateLimiter.reset();
      });

  #### Since

  0.8.0

  - Defined in utils/rateLimiter.ts:361

### tryRemoveTokens

- tryRemoveTokens(count: number): boolean

  Attempts to consume `count` tokens without throwing on failure.

  Synchronous alternative to removeTokens that returns `false` instead of waiting when the bucket lacks tokens. Useful in hot paths where callers want to branch on availability rather than await a refill.

  Note: This method still throws for invalid `count` arguments (non-integer, `< 1`, or exceeding bucket capacity). It only avoids throwing when there are insufficient tokens in the bucket at the time of the call.

  #### Parameters

  - count: number

    Number of tokens to consume (must be a finite integer ≥ 1 and ≤ `tokensPerInterval`); throws for invalid values

  #### Returns boolean

  `true` if tokens were successfully consumed, `false` if the bucket did not have enough tokens (bucket is left unchanged)

  #### Example

      if (!rateLimiter.tryRemoveTokens(1)) {
        return { error: 'Rate limit exceeded. Please try again later.' };
      }
      const data = await fetchFromEPAPI('/meps');

  #### Since

  0.8.0

  - Defined in utils/rateLimiter.ts:256

### `Private` `Static` resolveTimeout

- resolveTimeout(rawTimeoutMs: number | undefined): number

  Coerce an optional timeoutMs value to a safe finite number >= 0.

  #### Parameters

  - rawTimeoutMs: number | undefined

  #### Returns number

  - Defined in utils/rateLimiter.ts:123