T-Invest Node SDK Node.js
On this page

Implement a custom unary gRPC limiter

Use this example when you need a different algorithm or want to coordinate quotas across processes. The application implements TInvestUnaryLimiter, waits for a permit for the supplied quota, and stops waiting on AbortSignal. The SDK calls the same interface before each unary request and leaves control of the queue, storage, and coordinator failures to the application.

See Request rate limiting to enable the built-in limiter, override quotas, or set quotaShare.

Define what the SDK and limiter each control

The SDK handles the T-Invest API rules.

  • Match the full gRPC method path to the service rule or a more specific method rule.
  • Combine methods that spend a shared quota under one bucket.
  • Pass the original maxRequests and windowMs, preserving second-long windows.
  • Combine cancellation of a specific RPC with SDK instance closure.

The application limiter determines when to permit the next request.

  • Choose a waiting algorithm.
  • Store or coordinate state.
  • Decide which processes, machines, or deployments share that state.
  • Stop waiting on AbortSignal.
  • Handle failures of the limiter's storage or service.

The SDK supplies quota data without the OAuth token, request body, metadata, or service client. Use explicit coordination keys for external storage.

Import the public types

Import the types from the package root.

unary-limiter-types.ts
import type {
  TInvestUnaryLimit,
  TInvestUnaryLimitContext,
  TInvestUnaryLimiter,
  TInvestUnaryLimits,
  TInvestUnaryQuota
} from '@woodger/t-invest-node-sdk';

The interface is defined as follows.

unary-limiter-contract.ts
interface TInvestUnaryLimit {
  readonly maxRequests: number;
  readonly windowMs: number;
}

type TInvestUnaryLimits = Record<string, TInvestUnaryLimit>;

interface TInvestUnaryQuota extends TInvestUnaryLimit {
  readonly bucket: string;
}

interface TInvestUnaryLimitContext {
  readonly path: string;
  readonly quota: TInvestUnaryQuota;
  readonly signal: AbortSignal;
}

interface TInvestUnaryLimiter {
  acquire(context: TInvestUnaryLimitContext): Promise<void>;
}

Pass any object that structurally implements TInvestUnaryLimiter to TInvestOptions.unaryLimiter.

Understand when acquire() runs

Each unary RPC goes through the following steps.

Code
проверка lifecycle SDK
  -> разрешение path в quota
  -> unaryLimiter.acquire(context)
  -> повторная проверка lifecycle и AbortSignal
  -> передача request в gRPC transport

The following rules apply.

  1. The SDK calls acquire() exactly once just before each attempt to pass a unary request to the transport.
  2. When Promise<void> resolves, the limiter has granted a permit. The SDK may start the gRPC call immediately.
  3. If the promise rejects, the SDK skips sending the request and propagates the original limiter error without wrapping it as a transport SdkError.
  4. Server-side and bidirectional streams bypass this interface. Their connections and subscriptions have their own limits.
  5. When unaryLimiter is omitted, the SDK passes the unary call to the transport immediately.

The limiter runs in transport middleware, so all public service clients use the same contract. A successful acquire() grants local permission to continue. The provider still decides whether to accept the request.

Use the values passed to acquire()

acquire() receives the context of a single RPC. Use path to identify the method, quota to track requests, and signal to stop waiting for permission to proceed.

Use path for diagnosis

path is the full path of the called RPC.

Code
/tinkoff.public.invest.api.contract.v1.MarketDataService/GetCandles

Use it for diagnosis, metrics, and extra application rules. The SDK provides the resolved rule in quota.

Use quota.bucket for shared accounting

bucket is an opaque identifier for shared time-based state. Equal values mean the calls must use a shared queue or counter. For example, several report generation methods may receive the same bucket.

Application code should follow these rules.

  • Use the entire value.
  • Compare it only for equality.
  • Treat any prefixes and segments as internal to the SDK.
  • Keep business meaning and persistent formats independent of the identifier.
  • Add a coordination scope as a separate field or an external prefix if one store or service serves multiple users, environments, or servers.

Treat bucket values as part of a specific SDK release's quota rules. Check the compatibility of the rules when different versions of the package run together.

Use quota.maxRequests and quota.windowMs together

The pair specifies the maximum number of requests in the original time window.

unary-quota.ts
{
  bucket: '...',
  maxRequests: 15,
  windowMs: 1_000
}

This means 15 requests per second. A limit of 900 requests per minute allows a different burst size.

The SDK passes finite positive values from its static rules with TInvestOptions.unaryLimits overrides. Look up the current user tariff separately. The limiter can enforce stricter application rules and consider x-ratelimit-* metadata or getUserTariff() data without mutating the object it receives.

Each call receives the most specific matching rule. Apply additional service, user, or IP limits in the application.

Stop waiting on signal

The SDK aborts signal when the call is canceled or when sdk.close() runs. The signal may come from AbortSignal.any(). Use its state and events without comparing its identity to the signal in the call options.

The implementation should follow these rules.

  • Check signal.aborted before queueing.
  • Remove a pending wait on the abort event.
  • Reject the promise with signal.reason when available.
  • Remove the event handler on every completion path.
  • Grant permits only while the request is active.

If the limiter ignores the signal and leaves the promise pending, its wait can outlive sdk.close() and the RPC will continue to await a permit.

The SDK turns cancellation of an individual call into public SdkErrorCode.Cancelled with source: 'abort'. Closing the SDK keeps the SDK-closed error. Other limiter errors propagate in their original form.

Manage the limiter lifecycle

The code that creates a limiter owns its lifecycle.

  • TInvestNodeSDK.close() leaves the limiter's close(), dispose(), and any other shutdown methods to the caller.
  • Share one limiter across SDK instances that need shared state.
  • Separate limiter objects have independent state by default.
  • Close external connections and stop workers after all SDK instances using the limiter have shut down.

This example shares one limiter across two SDK instances in one process.

shared-unary-limiter.ts
import { TInvestNodeSDK, type TInvestUnaryLimiter } from '@woodger/t-invest-node-sdk';

declare const unaryLimiter: TInvestUnaryLimiter;

const firstSdk = new TInvestNodeSDK({
  token,
  endpoint,
  unaryLimiter
});

const secondSdk = new TInvestNodeSDK({
  token,
  endpoint,
  unaryLimiter
});

try {
  const results = await Promise.allSettled([
    firstSdk.marketData.getCandles(firstRequest),
    secondSdk.marketData.getCandles(secondRequest)
  ]);

  for (const result of results) {
    if (result.status === 'rejected') {
      throw result.reason;
    }
  }
}
finally {
  firstSdk.close();
  secondSdk.close();
}

Promise.allSettled() waits for both requests even if one fails. Then the example propagates the error and closes both SDK instances in finally.

If instances use different unaryLimits, the same bucket can receive different settings. Explicitly choose how to handle conflicts. You can reject them, use the strictest quota, or separate the coordination scopes.

Implement a limiter for one process

This application-side implementation uses a sliding window. It permits bursts within a quota and holds state in the current process. For maxRequests >= 1, round the burst size down. For maxRequests < 1, grant one request per longer window of windowMs / maxRequests. A quota of 0.5 per 100 ms allows one request every 200 ms.

rolling-window-unary-limiter.ts
import type {
  TInvestUnaryLimitContext,
  TInvestUnaryLimiter,
  TInvestUnaryQuota
} from '@woodger/t-invest-node-sdk';

interface BucketState {
  readonly maxRequests: number;
  readonly windowMs: number;
  readonly issuedAt: number[];
}

const maxTimerDelayMs = 2_147_483_647;

export class RollingWindowUnaryLimiter implements TInvestUnaryLimiter {
  private readonly buckets = new Map<string, BucketState>();

  async acquire(context: TInvestUnaryLimitContext): Promise<void> {
    const state = this.getBucket(context.quota);
    const maxRequests = Math.max(1, Math.floor(state.maxRequests));
    const windowMs = state.maxRequests < 1
      ? state.windowMs / state.maxRequests
      : state.windowMs;

    while (true) {
      throwIfAborted(context.signal);

      const now = performance.now();

      this.removeExpired(state, now, windowMs);

      if (state.issuedAt.length < maxRequests) {
        state.issuedAt.push(now);

        return;
      }

      const oldestPermit = state.issuedAt[0];

      if (oldestPermit === undefined) {
        continue;
      }

      await wait(
        Math.max(0, oldestPermit + windowMs - now),
        context.signal
      );
    }
  }

  private getBucket(quota: TInvestUnaryQuota): BucketState {
    const current = this.buckets.get(quota.bucket);

    if (current !== undefined) {
      if (
        current.maxRequests !== quota.maxRequests
        || current.windowMs !== quota.windowMs
      ) {
        throw new Error(`Conflicting quota for bucket ${quota.bucket}`);
      }

      return current;
    }

    const created: BucketState = {
      maxRequests: quota.maxRequests,
      windowMs: quota.windowMs,
      issuedAt: []
    };

    this.buckets.set(quota.bucket, created);

    return created;
  }

  private removeExpired(state: BucketState, now: number, windowMs: number): void {
    const threshold = now - windowMs;
    let expired = 0;

    while (
      expired < state.issuedAt.length
      && (state.issuedAt[expired] ?? Number.POSITIVE_INFINITY) <= threshold
    ) {
      expired += 1;
    }

    if (expired > 0) {
      state.issuedAt.splice(0, expired);
    }
  }
}

async function wait(delayMs: number, signal: AbortSignal): Promise<void> {
  let remainingMs = delayMs;

  while (remainingMs > 0) {
    throwIfAborted(signal);

    const startedAt = performance.now();

    await waitOnce(Math.min(remainingMs, maxTimerDelayMs), signal);
    remainingMs -= performance.now() - startedAt;
  }
}

function waitOnce(delayMs: number, signal: AbortSignal): Promise<void> {
  return new Promise<void>((resolve, reject) => {
    if (signal.aborted) {
      reject(abortReason(signal));

      return;
    }

    const onAbort = () => {
      clearTimeout(timer);
      signal.removeEventListener('abort', onAbort);
      reject(abortReason(signal));
    };
    const timer = setTimeout(() => {
      signal.removeEventListener('abort', onAbort);
      resolve();
    }, delayMs);

    signal.addEventListener('abort', onAbort, { once: true });
  });
}

function throwIfAborted(signal: AbortSignal): void {
  if (signal.aborted) {
    throw abortReason(signal);
  }
}

function abortReason(signal: AbortSignal): unknown {
  if (signal.reason !== undefined) {
    return signal.reason;
  }

  const error = new Error('The operation was aborted');

  error.name = 'AbortError';

  return error;
}

Pass the same limiter object to every SDK instance in the process that shares a quota.

rolling-window-unary-limiter.ts
import { TInvestNodeSDK } from '@woodger/t-invest-node-sdk';

const unaryLimiter = new RollingWindowUnaryLimiter();

const sdk = new TInvestNodeSDK({
  token,
  endpoint,
  unaryLimiter
});

Decide how the application observes the limiter, bounds the queue, orders permits, handles overload, and removes unused bucket entries. The SDK contract is the TInvestUnaryLimiter interface.

Coordinate quotas across processes

One JavaScript object shares state among SDK instances in a single process. Across processes, acquire() can call a separately running coordinator.

When a coordinator serves multiple users, environments, or deployments, include a key to identify shared accounting. This example uses an application protocol field called quotaCoordinationKey, separate from the SDK interface.

coordinator-unary-limiter.ts
import type { TInvestUnaryLimitContext, TInvestUnaryLimiter } from '@woodger/t-invest-node-sdk';

interface CoordinatorClient {
  acquire(
    request: {
      readonly quotaCoordinationKey: string;
      readonly bucket: string;
      readonly maxRequests: number;
      readonly windowMs: number;
    },
    signal: AbortSignal
  ): Promise<void>;
}

class CoordinatorUnaryLimiter implements TInvestUnaryLimiter {
  constructor(
    private readonly client: CoordinatorClient,
    private readonly quotaCoordinationKey: string
  ) {}

  async acquire(context: TInvestUnaryLimitContext): Promise<void> {
    await this.client.acquire({
      quotaCoordinationKey: this.quotaCoordinationKey,
      bucket: context.quota.bucket,
      maxRequests: context.quota.maxRequests,
      windowMs: context.quota.windowMs
    }, context.signal);
  }
}

Decide the following for the coordinator.

  • Which code starts and stops it.
  • Which processes use the same quotaCoordinationKey.
  • How it reserves request permits atomically.
  • Whether it removes a pending request upon cancellation or disconnect.
  • Whether it blocks permits while the coordinator is unavailable.
  • How it starts after losing in-memory state.
  • How it handles different SDK versions or incompatible quotas for the same bucket.
  • Which integration tests cover concurrent operation, a crash, and a restart.

Keep the permit spent after an RPC error or cancellation. The request may already have reached the provider and counted against its quota.

The application chooses its coordinator protocol, IPC transport or database, and coordination key and how to communicate it. These choices stay outside the SDK dependency graph.

Verify a custom implementation

  • acquire() succeeds only after a permit is granted.
  • Calls with the same bucket and quotaCoordinationKey use one shared state.
  • maxRequests and windowMs are applied together in the original units.
  • signal cancellation removes pending waits without leaking event handlers.
  • Quota stays spent after a permit is issued.
  • Conflicting quota settings for one bucket are handled explicitly.
  • A storage or service error preserves the configured failure behavior and does not silently switch to local limits.
  • Only unary calls count toward unary quotas.
  • The limiter works with quota information alone, without the OAuth token or request body.
  • The application manages the limiter's lifecycle.
  • Where the implementation supports cross-process coordination, a dedicated integration test verifies it.

See the limits policy for official quota values and package rules and the roadmap for cross-process architectures and their trade-offs.