Golem quota effect

From golemcloud/golem · View interactive version

Golem quota effect is an AI agent skill from the GitHub repository golemcloud/golem. Adding resource quotas to an Effect-based Golem agent. Use when the user asks about rate limiting, resource quotas, Quota tokens, Quota.acquireQuotaToken, Quota.withReservation, throttling API calls, limiting concurrency, capacity limits, or splitting tokens between agents.

How to use this skill

Skill file

Adding Resource Quotas to an Effect Golem Agent

Golem provides distributed resource quotas through the Quota namespace from

@golemcloud/effect-golem. The manifest defines each resource's policy; agent code acquires a

token for that resource and performs Effect-based reservations against it.

1. Define Resources in the Application Manifest

Add resource definitions under resourceDefaults in golem.yaml, scoped per environment:

resourceDefaults:
  prod:
    api-calls:
      limit:
        type: Rate
        value: 100
        period: minute
        max: 1000
      enforcementAction: reject
      unit: request
      units: requests
    storage:
      limit:
        type: Capacity
        value: 1073741824 # 1 GB
      enforcementAction: reject
      unit: byte
      units: bytes
    connections:
      limit:
        type: Concurrency
        value: 50
      enforcementAction: throttle
      unit: connection
      units: connections

Limit Types

capped at max. Use it for API-call rates.

storage or budget limits.

connections or jobs.

Enforcement Actions

Quota.FailedReservationError, whose estimatedWaitNanos is bigint | undefined.

The resource name passed from code must exactly match the manifest key. Do not recreate limit or

enforcement policy in the Effect implementation.

2. Acquire and Reuse a Token

Import Effect APIs from effect and quota APIs through the SDK's Quota namespace:

import { Effect, Schema } from "effect";
import { defineAgent, method, Quota } from "@golemcloud/effect-golem";

Quota.acquireQuotaToken is an Effect. Acquire it once in the agent's init Effect

and pass it to methods as state. This is the Effect equivalent of keeping

the token in the constructed agent's state; do not acquire a new token for every invocation or at

module top level.

const QuotaCallResult = Schema.Struct({
  input: Schema.String,
  success: Schema.Boolean,
});

export const QuotaAgent = defineAgent({
  name: "QuotaAgent",
  mode: "durable",
  id: { instanceName: Schema.String },
  methods: {
    rateLimitedCall: method({
      input: { input: Schema.String },
      success: QuotaCallResult,
    }),
  },
}).implement({
  init: () => Quota.acquireQuotaToken("api-calls", 1n),
  methods: (token) => ({
      rateLimitedCall: ({ input }) =>
        Quota.withReservation(token, 1n, () =>
          Effect.succeed({
            used: 1n,
            value: { input, success: true },
          }),
        ).pipe(
          Effect.catchTag("FailedReservationError", () =>
            Effect.succeed({ input, success: false }),
          ),
          Effect.orDie,
        ),
  }),
});

The second acquisition argument is the expected amount per reservation and is used for fair

scheduling. All quota amounts are bigint values. In the example, Effect.catchTag recovers only

the normal reject outcome; Effect.orDie converts the remaining unexpected QuotaHostError into

an invocation failure instead of incorrectly reporting quota exhaustion. If callers should

recover from host failures, map them to a domain error declared by the method instead.

3. Reserve Fixed or Variable Costs

Quota.withReservation reserves an amount, runs an Effect, commits the reported usage, and returns

the callback's value:

const response = yield* Quota.withReservation(token, 1n, () =>
  callSimpleApi().pipe(
    Effect.map((value) => ({
      used: 1n,
      value,
    })),
  ),
);

For variable-cost work, reserve the maximum expected cost and report actual usage:

const response = yield* Quota.withReservation(token, 4_000n, () =>
  Effect.gen(function* () {
    const result = yield* callLlm(prompt, { maxTokens: 4_000 });
    return {
      used: BigInt(result.tokensUsed),
      value: result,
    };
  }),
);

The callback must return an Effect whose success value is { used: bigint, value: A }.

Quota.withReservation already manages its own scope; do not add a redundant Effect.scoped

around it. If the callback fails, dies, or is interrupted, the reservation finalizer commits 0n

and preserves the original cause.

4. Reserve and Commit Manually

Use Quota.reserve and Quota.commit for finer control. A manual reservation requires a Scope, so

wrap the complete lifetime in Effect.scoped:

const result = yield* Effect.scoped(
  Effect.gen(function* () {
    const reservation = yield* Quota.reserve(token, 100n);
    const result = yield* doWork();
    yield* Quota.commit(reservation, BigInt(result.actualUsage));
    return result;
  }),
);

Committing less than the reserved amount returns unused capacity. Committing more records debt

against the token. If the scope closes before an explicit commit, the SDK performs a best-effort

commit(0n); a successful explicit commit makes that finalizer a no-op.

5. Split Tokens Across Agent RPC

Use Quota.QuotaTokenSchema (or Quota.quotaTokenSchema({ resourceName: "api-calls" })) as

the Effect Schema for quota-token method parameters and results. Quota.QuotaToken is the opaque

handle class, not a schema. The SDK codec transfers ownership of the live token through RPC;

it does not produce a reusable wire record:

const SummaryResult = Schema.Struct({
  summary: Schema.String,
  token: Quota.QuotaTokenSchema,
});

const summarize = method({
  input: {
    text: Schema.String,
    token: Quota.QuotaTokenSchema,
  },
  success: SummaryResult,
});

Split from the parent, send the child token through an existing typed agent client, and merge the

returned token:

After the RPC transfers childToken, the sender must not reserve with it, send it again, or

merge that original handle. Only the token returned by the callee can be merged back. A caller

must not assume ownership returns when an RPC fails after transfer.

const parentToken = yield* Quota.acquireQuotaToken("api-calls", 400n);
const childToken = yield* Quota.split(parentToken, 200n);
const summarizer = yield* SummarizerAgent.client.upsert({ name: "sum-1" });
const { summary, token: returnedToken } = yield* summarizer.summarize({
  text,
  token: childToken,
});
yield* Quota.merge(parentToken, returnedToken);
return summary;

Quota.split fails with QuotaHostError if the child expected use exceeds the parent's current

expected use. Quota.merge requires tokens from the same resource and environment. A successful

merge consumes the returned child token, so do not use it afterward.

6. Update a Deployed Resource

Resource updates affect running agents without changing their Effect code:

golem resource update api-calls --limit '{"type":"Rate","value":200,"period":"minute","max":2000}' --environment prod

Key Constraints

host quota client is internal.

Quota.reserve / Quota.commit lifetimes.

a broad catch that also hides body failures or QuotaHostError.

opaque Quota.QuotaToken class. Tokens cannot be serialized as ordinary JSON or snapshot state.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.