Skip to content

Quota configuration reference

echo.labstack.com/pro v0.2.0. See the task guide for setup examples.

  • Config.Store and Config.Plans: a store and at least one plan.
  • MiddlewareConfig.Identity: the paying subject from verified application data.
  • MiddlewareConfig.Plan: required with several plans; nil selects the only configured plan.
  • MiddlewareConfig.Period: required for billing-period limits.

Redis constructors check options without connecting; your application owns and closes the client.

Import echo.labstack.com/pro/quota.

quota.Config · quota/config.go:19 · echo.labstack.com/[email protected]

Config configures immutable plans and synchronous hooks.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
StoreStoreStore is required, retained and caller-owned; Limiter.Close never closes it.Store is required, retained and caller-owned; Limiter.Close never closes it.quota/config.go:22
Plans[]PlanPlans requires at least one valid plan; New copies all maps and slices.Plans requires at least one valid plan; New copies all maps and slices.quota/config.go:25
StoreTimeouttime.DurationStoreTimeout bounds each remote store call; zero uses 25ms, negative is invalid, and caller deadlines always win. Local stores, such as memory, run without it.StoreTimeout bounds each remote store call; zero uses 25ms, negative is invalid, and caller deadlines always win.quota/config.go:29
DenyCachetime.DurationDenyCache is off at zero; positive durations at most 10s cache store denials.DenyCache is off at zero; positive durations at most 10s cache store denials.quota/config.go:31
DenyCacheSizeintDenyCacheSize bounds the LRU; zero defaults to 10000, otherwise it must be positive.DenyCacheSize bounds the LRU; zero defaults to 10000, otherwise it must be positive.quota/config.go:34
ReservationTTLtime.DurationReservationTTL defaults to 1h and must be at least 1ms; size it above the longest work plus settlement.ReservationTTL defaults to 1h and must be at least 1ms; size it above the longest work plus settlement.quota/config.go:37
SettledRetentiontime.DurationSettledRetention defaults to 5m, must be at least 1ms, and bounds the idempotent retry window.SettledRetention defaults to 5m, must be at least 1ms, and bounds the idempotent retry window.quota/config.go:40
SettleWorkersintSettleWorkers defaults to 4 (1–1024); the queue holds 1024 jobs.SettleWorkers defaults to 4 (1–1024); the queue holds 1024 jobs.quota/config.go:42
ExpiredSettlePolicyExpired settles reservations past ReservationTTL: Keep (default) commits reserved amounts, Refund returns them. It runs on the next Reserve or Settle in the partition and, with an Outbox, in the periodic sweep.Expired settles reservations past ReservationTTL: Keep (default) commits reserved amounts, Refund returns them.quota/config.go:46
Outbox*OutboxOutbox makes consumption and threshold events durable and is copied when nonnil; with it, Hooks.OnConsumption and Hooks.OnThreshold must be nil. New then starts background delivery goroutines, with partition concurrency bounded by Outbox.Workers; Close stops them. Nil disables durable delivery; Hooks then receive events at most once.Outbox makes consumption and threshold events durable and is copied when nonnil; with it, Hooks.OnConsumption and Hooks.OnThreshold must be nil. Nil disables durable delivery; Hooks then receive events at most once.quota/config.go:52
FallbackFallbackFallback applies only to buckets in a remote store. If the remote store fails, counters allow requests unless the limit is strict. The zero value enables local fallback for remote buckets with one instance and up to 100,000 local keys.The zero value enables local fallback for remote buckets with one instance and up to 100,000 local keys.quota/config.go:56
BreakerBreakerBreaker selects bounded remote-store failure tracking; zero uses Breaker defaults.Breaker selects bounded remote-store failure tracking; zero uses Breaker defaults.quota/config.go:59
HooksHooksHooks contains optional retained synchronous callbacks; see Hooks for concurrency.Hooks contains optional retained synchronous callbacks; see Hooks for concurrency.quota/config.go:62
Logger*slog.LoggerLogger is retained and caller-owned; nil is silent.Logger is retained and caller-owned; nil is silent.quota/config.go:64
Functions from package source
TypeSource
func New(cfg Config) (*Limiter, error)quota/limiter.go:45

Import echo.labstack.com/pro/quota.

quota.MiddlewareConfig · quota/middleware.go:26 · echo.labstack.com/[email protected]

MiddlewareConfig binds a concurrent Limiter to Echo. Callbacks run synchronously and must support concurrent requests. The request context controls store cancellation. Settle jobs retain a cancellation-detached request context, never the Echo context. The caller owns and closes Limiter. Defaults are applied to a private copy. Concurrency slots are released after the handler returns or panics, on the settle worker pool.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
ExclusiveboolExclusive rejects a second quota check on the same Limiter with ErrDuplicateAdmission. Earlier usage stays counted. Skips and callback failures do not count as checks; all Allow and Reserve outcomes do. Request state tracks at most eight distinct Limiters. An Exclusive check on a ninth Limiter returns ErrParticipationLimit. Further non-Exclusive checks run without tracking. Exclusive defaults to false.Exclusive defaults to false.quota/middleware.go:32
SettleboolSettle reserves before the handler and asynchronously settles final costs afterward. Settle defaults to false, charging usage without reserving and settling.Settle defaults to false, charging usage without reserving and settling.quota/middleware.go:35
Unsettledfunc(status int) SettlePolicyUnsettled defaults to Keep; it selects a policy only when Charge was not called.Unsettled defaults to Keep; it selects a policy only when Charge was not called.quota/middleware.go:37
Limiter*LimiterLimiter is required, retained and caller-owned.Limiter is required, retained and caller-owned.quota/middleware.go:39
Identityfunc(*echo.Context) (Identity, error)Identity is required and resolves a trusted paying subject.Identity is required and resolves a trusted paying subject.quota/middleware.go:41
Planfunc(*echo.Context, Identity) (string, error)Plan is optional only with one configured plan; nil selects that plan.Plan is optional only with one configured plan; nil selects that plan.quota/middleware.go:44
Periodfunc(*echo.Context, Identity) (Period, error)Period is required for selected billing-period limits; nil supplies no period.Period is required for selected billing-period limits; nil supplies no period.quota/middleware.go:47
Overridesfunc(*echo.Context, Identity, string) ([]Override, error)Overrides runs for both middleware and UsageHandler. Your application should cache the data it reads. Nil applies no numeric overrides.Nil applies no numeric overrides.quota/middleware.go:50
Shadowfunc(*echo.Context, Identity, string) (string, error)Shadow selects a candidate plan for limit checks only; nil disables it.Shadow selects a candidate plan for limit checks only; nil disables it.quota/middleware.go:52
Dimensionsfunc(*echo.Context) (map[string]string, error)Dimensions selects trusted subjects in middleware; UsageHandler uses query values. Dimensions is optional; nil supplies no dimension values during limit checks.Dimensions is optional; nil supplies no dimension values during limit checks.quota/middleware.go:55
Costfunc(*echo.Context) (Cost, error)Cost is optional; nil charges requests:1. Returned maps are borrowed for the request and must not be mutated concurrently.Cost is optional; nil charges requests:1.quota/middleware.go:58
Operationfunc(*echo.Context) stringOperation defaults to the registered method/path, with automatic HEAD using GET and unmatched requests sharing one operation.Operation defaults to the registered method/path, with automatic HEAD using GET and unmatched requests sharing one operation.quota/middleware.go:61
Skippermiddleware.SkipperSkipper defaults to nil, which skips nothing. When it returns true, quota does not check or charge the request.Skipper defaults to nil, which skips nothing.quota/middleware.go:64
HeadersHeaderModeHeaders defaults to Draft11; Legacy, Draft11AndLegacy and NoHeaders select other modes.Headers defaults to Draft11; Legacy, Draft11AndLegacy and NoHeaders select other modes.quota/middleware.go:67
DenyHandlerfunc(*echo.Context, Decision) errorDenyHandler defaults to the package RFC 9457 denial renderer.DenyHandler defaults to the package RFC 9457 denial renderer.quota/middleware.go:69
UnavailableHandlerfunc(*echo.Context, Decision) errorUnavailableHandler defaults to the package RFC 9457 unavailable renderer.UnavailableHandler defaults to the package RFC 9457 unavailable renderer.quota/middleware.go:72
ErrorHandlerfunc(*echo.Context, error) errorErrorHandler defaults to returning input errors unchanged to Echo.ErrorHandler defaults to returning input errors unchanged to Echo.quota/middleware.go:74
Functions from package source
TypeSource
func (cfg MiddlewareConfig) ToMiddleware() (echo.MiddlewareFunc, error)quota/middleware.go:224

Import echo.labstack.com/pro/quota.

quota.MemoryConfig · quota/memory.go:18 · echo.labstack.com/[email protected]

MemoryConfig configures bounded process-local quota state.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
MaxKeysintMaxKeys defaults to 500000. Positive values cap keys separately for live state, reservations, credit records, generations and outbox entries. Negative values fail Validate and quota.New.MaxKeys defaults to 500000.quota/memory.go:22
Clockfunc() time.TimeClock is retained and must be concurrency safe; nil uses time.Now.Clock is retained and must be concurrency safe; nil uses time.Now.quota/memory.go:24
Functions from package source
TypeSource
func NewMemoryStore(cfg MemoryConfig) *MemoryStorequota/memory.go:79

Import echo.labstack.com/pro/quota/redisstore.

redisstore.Config · quota/redisstore/store.go:25 · echo.labstack.com/[email protected]

Config selects a key namespace. An optional namespace: prefix scopes keys to a shared Redis ACL, for example myapp:prod. Use at most 32 lowercase letters, digits, underscores or hyphens.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
PrefixstringPrefix defaults to quota; the unqualified prefix must match [a-z0-9][a-z0-9_]{0,15}. See Config for the optional namespace.Prefix defaults to quota; the unqualified prefix must match [a-z0-9][a-z0-9_]{0,15}. See Config for the optional namespace.quota/redisstore/store.go:28
Clockfunc() time.TimeClock is retained for isolated tests only and must be concurrency safe. It replaces server time, including virtual expiry; nil uses Redis TIME.It replaces server time, including virtual expiry; nil uses Redis TIME.quota/redisstore/store.go:31
Functions from package source
TypeSource
func New(client redis.UniversalClient, cfg Config) (*Store, error)quota/redisstore/store.go:80

Import echo.labstack.com/pro/quota.

quota.AdminConfig · quota/admin.go:22 · echo.labstack.com/[email protected]

AdminConfig mounts administration routes on a caller-owned Echo group. Authorization sees no target, so every route acts on any tenant: grant access only to global operators. POST bodies must be application/json; prefer bearer tokens to cookies. Callbacks must be concurrency safe; request cancellation controls store calls. Input/store errors are sanitized problems.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
Limiter*LimiterLimiter is required, retained and caller-owned.Limiter is required, retained and caller-owned.quota/admin.go:24
Authorizefunc(*echo.Context) errorAuthorize is required and runs before parsing or store access on every route. It must not retain c.Authorize is required and runs before parsing or store access on every route.quota/admin.go:27
Overridesfunc(*echo.Context, Identity, string) ([]Override, error)Overrides optionally changes limit numbers for /usage; nil uses plan values.Overrides optionally changes limit numbers for /usage; nil uses plan values.quota/admin.go:30
TopK*TopKTopK is optional and caller-owned; nil makes /top return not found.TopK is optional and caller-owned; nil makes /top return not found.quota/admin.go:32
ErrorHandlerfunc(*echo.Context, error) errorErrorHandler optionally handles authorization errors; nil returns them to Echo.ErrorHandler optionally handles authorization errors; nil returns them to Echo.quota/admin.go:35

Import echo.labstack.com/pro/quota.

quota.Breaker · quota/config.go:79 · echo.labstack.com/[email protected]

Breaker configures a remote-store rolling failure ratio. Samples are bucketed by Window/256 (at least 1ms) to bound memory. Calls whose caller canceled are not counted; calls that outlive a caller deadline count as failures.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
Windowtime.DurationWindow defaults to 10s; valid range 1ms–24h.Window defaults to 10s; valid range 1ms–24h.quota/config.go:81
MinCallsintMinCalls defaults to 20; nonzero values must be positive.MinCalls defaults to 20; nonzero values must be positive.quota/config.go:83
FailureRatiofloat64FailureRatio defaults to 0.5. Nonzero values must be greater than 0 and at most 1. NaN is invalid.FailureRatio defaults to 0.5. Nonzero values must be greater than 0 and at most 1.quota/config.go:86
Cooldowntime.DurationCooldown defaults to 1s; nonzero values must be positive.Cooldown defaults to 1s; nonzero values must be positive.quota/config.go:88

Import echo.labstack.com/pro/quota.

quota.Fallback · quota/config.go:68 · echo.labstack.com/[email protected]

Fallback configures remote-store local buckets.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
DisabledboolDisabled turns off local fallback; default false.Disabled turns off local fallback; default false.quota/config.go:70
InstancesintInstances defaults to 1 and MaxKeys to 100000; both must be positive after defaults.Instances defaults to 1 and MaxKeys to 100000; both must be positive after defaults.quota/config.go:73
MaxKeysintInstances defaults to 1 and MaxKeys to 100000; both must be positive after defaults.Instances defaults to 1 and MaxKeys to 100000; both must be positive after defaults.quota/config.go:73

Import echo.labstack.com/pro/quota.

quota.Hooks · quota/config.go:99 · echo.labstack.com/[email protected]

Hooks run synchronously, without panic recovery, on the calling goroutine. Callbacks must support concurrent use; blocking delays the request. All are optional. Consumption and threshold delivery is at-most-once. OnStoreError operations include admit, reserve, settle, usage, reset, shadow, release, credits, expire and outbox. A shadow-only failure calls OnStoreError once with a *StoreError and operation shadow; live limit checks and Decision.Err are unaffected. Lifecycle observations run once per normally returning call or worker job, after other hooks and cache invalidation. OnOperation runs last. They count attempts, never consumption. Application panics propagate.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
OnDecisionfunc(context.Context, Request, Decision)OnDecision is optional; nil disables this callback.OnDecision is optional; nil disables this callback.quota/config.go:102
OnStoreErrorfunc(context.Context, string, error)OnStoreError is optional; nil disables this callback.OnStoreError is optional; nil disables this callback.quota/config.go:104
OnConsumptionfunc(context.Context, ConsumptionEvent)OnConsumption is optional; nil disables this callback.OnConsumption is optional; nil disables this callback.quota/config.go:106
OnThresholdfunc(context.Context, ThresholdEvent)OnThreshold is optional; nil disables this callback.OnThreshold is optional; nil disables this callback.quota/config.go:108
OnSettlementfunc(context.Context, SettlementObservation)OnSettlement is optional; nil disables this callback.OnSettlement is optional; nil disables this callback.quota/config.go:110
OnCreditfunc(context.Context, CreditObservation)OnCredit is optional; nil disables this callback.OnCredit is optional; nil disables this callback.quota/config.go:112
OnReleasefunc(context.Context, ReleaseObservation)OnRelease is optional; nil disables this callback.OnRelease is optional; nil disables this callback.quota/config.go:114
OnResetfunc(context.Context, ResetObservation)OnReset is optional; nil disables this callback.OnReset is optional; nil disables this callback.quota/config.go:116
ObserveOperationfunc(context.Context) boolObserveOperation gates only OnOperation and its aggregate construction. Nil observes every operation. It runs once per public operation or worker job with that operation's context; a panic is recovered and means true. Lifecycle callbacks are unaffected. It must be safe for concurrent calls and should return promptly without retaining the context.Nil observes every operation.quota/config.go:122
OnOperationfunc(context.Context, OperationObservation)OnOperation is optional; nil disables this callback.OnOperation is optional; nil disables this callback.quota/config.go:124

Import echo.labstack.com/pro/quota.

quota.Outbox · quota/outbox.go:24 · echo.labstack.com/[email protected]

Outbox delivers consumption and threshold events durably. The store writes each event in the same atomic step that changes usage, so events are as durable as the store. The zero value is invalid: Deliver is required. New copies settings and retains Deliver. Call Limiter.Close to stop delivery. Close does not cancel Deliver's context; Deliver must bound its work and return for Close to finish.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
Deliverfunc(context.Context, Event) errorDeliver receives every event at least once, possibly concurrently and out of order. Return nil after durably handling it; an error retries with backoff. Deduplicate by Event.ID. It must support concurrent calls.Return nil after durably handling it; an error retries with backoff.quota/outbox.go:28
WorkersintWorkers sets how many partitions deliver at once. Default 2; valid range 1–64.Default 2; valid range 1–64.quota/outbox.go:30
BatchintBatch sets how many entries each store call reads. Default 100; valid range 1–1000.Default 100; valid range 1–1000.quota/outbox.go:32
PollIntervaltime.DurationPollInterval sets the index poll interval and first retry delay. Default 1s; minimum 1ms.Default 1s; minimum 1ms.quota/outbox.go:35
SweepIntervaltime.DurationSweepInterval sets the re-index and expiry sweep interval. Default 1m; minimum 1ms.Default 1m; minimum 1ms.quota/outbox.go:37

Import echo.labstack.com/pro/quota/quotaadmin.

quotaadmin.Config · quota/quotaadmin/panel.go:24 · echo.labstack.com/[email protected]

Config selects a constructed limiter.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
EnableCreditsboolEnableCredits exposes credit-topup and credit-correct. Mount then requires Keys and a durable Audit sink or explicit AllowUnauditedWrites.Mount then requires Keys and a durable Audit sink or explicit AllowUnauditedWrites.quota/quotaadmin/panel.go:27
EnableResetboolEnableReset exposes destructive partition-wide generation resets. Mount requires Keys and an Audit sink or explicit AllowUnauditedWrites.Mount requires Keys and an Audit sink or explicit AllowUnauditedWrites.quota/quotaadmin/panel.go:30
TopK*quota.TopKTopK optionally enables the top-consumption view; nil omits it. It remains caller-owned.TopK optionally enables the top-consumption view; nil omits it.quota/quotaadmin/panel.go:33
Denials*DenialRecorderDenials optionally supplies instance-local denials; nil omits that view. It remains caller-owned.Denials optionally supplies instance-local denials; nil omits that view.quota/quotaadmin/panel.go:36
BacklogBacklogBacklog optionally supplies outbox observations; nil omits that view. It remains caller-owned.Backlog optionally supplies outbox observations; nil omits that view.quota/quotaadmin/panel.go:39
IDstringID defaults to quota; use 1–32 lowercase ASCII letters, digits or hyphens, starting with a letter, excluding api and assets.ID defaults to quota; use 1–32 lowercase ASCII letters, digits or hyphens, starting with a letter, excluding api and assets.quota/quotaadmin/panel.go:42
Limiter*quota.LimiterLimiter is required, constructed and caller-owned; keep it open while serving.Limiter is required, constructed and caller-owned; keep it open while serving.quota/quotaadmin/panel.go:45
Overridesfunc(context.Context, quota.Identity, string) ([]quota.Override, error)Overrides optionally supplies read-only limit adjustments after authorization; nil uses plan values. The callback is retained, must be concurrency safe and must honor ctx.Overrides optionally supplies read-only limit adjustments after authorization; nil uses plan values.quota/quotaadmin/panel.go:49
Functions from package source
TypeSource
func New(cfg Config) (*Panel, error)quota/quotaadmin/panel.go:57

Import echo.labstack.com/pro/quota/quotamcp.

quotamcp.MiddlewareConfig · quota/quotamcp/config.go:36 · echo.labstack.com/[email protected]

MiddlewareConfig meters MCP tool calls with a quota.Limiter. Callbacks run on the request goroutine and must support concurrent calls. Configuration is copied by ToMiddleware; the caller owns and closes Limiter. Policies and their cost maps are copied; callbacks are retained and must honor cancellation. The middleware supports concurrent calls and owns no goroutines or client lifecycle.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
Limiter*quota.LimiterLimiter is required and caller-owned; quotamcp never closes it.Limiter is required and caller-owned; quotamcp never closes it.quota/quotamcp/config.go:38
Identityfunc(ctx context.Context, c Caller) (quota.Identity, error)Identity is required and returns the paying subject. It sees authenticated data only: ctx, Caller.TokenInfo and Caller.Header, never tool arguments.Identity is required and returns the paying subject.quota/quotamcp/config.go:42
Planfunc(ctx context.Context, id quota.Identity) (string, error)Plan selects a plan ID; nil uses the sole plan.Plan selects a plan ID; nil uses the sole plan.quota/quotamcp/config.go:44
Periodfunc(ctx context.Context, id quota.Identity) (quota.Period, error)Period returns the billing period; it is required and runs only for plans with billing-period limits.Period returns the billing period; it is required and runs only for plans with billing-period limits.quota/quotamcp/config.go:47
Overridesfunc(ctx context.Context, id quota.Identity, plan string) ([]quota.Override, error)Overrides changes limit numbers for one call; optional.Overrides changes limit numbers for one call; optional.quota/quotamcp/config.go:49
Shadowfunc(ctx context.Context, id quota.Identity, plan string) (string, error)Shadow selects a candidate plan for limit checks only; optional.Shadow selects a candidate plan for limit checks only; optional.quota/quotamcp/config.go:51
Dimensionsfunc(ctx context.Context, call Call) (map[string]string, error)Dimensions selects dimension values, for example the model a tool will call. It may read arguments; values select subjects, never the authenticated caller. Dimensions is optional; nil supplies no dimension values.Dimensions is optional; nil supplies no dimension values.quota/quotamcp/config.go:55
Policiesmap[string]PolicyPolicies maps tool names to metering policies; unlisted tools use Default with the operation Unlisted.Policies maps tool names to metering policies; unlisted tools use Default with the operation Unlisted.quota/quotamcp/config.go:58
DefaultPolicyDefault meters unlisted tools; zero charges one requests attempt with no billable Cost.Default meters unlisted tools; zero charges one requests attempt with no billable Cost.quota/quotamcp/config.go:61
Unsettledfunc(Outcome) quota.SettlePolicyUnsettled chooses what to do with a settled call that recorded no Charge. Nil keeps the reservation. A ChargeFirst call that never started refunds Cost without calling Unsettled. An input-required round also refunds Cost by default. Refunds never return Attempt meters.Nil keeps the reservation. An input-required round also refunds Cost by default.quota/quotamcp/config.go:66
DiscloseboolDisclose adds plan and limit names, quotas and balances to denials. Disclose defaults to false.Disclose defaults to false.quota/quotamcp/config.go:69
ReportUsageboolReportUsage adds the smallest remaining requests limit to the _meta of successful results. ReportUsage defaults to false.ReportUsage defaults to false.quota/quotamcp/config.go:73
LoopBreakerboolLoopBreaker adds the attempt meter LoopMeter and the dimension LoopDimension to every metered call, so a plan can limit identical calls. LoopBreaker defaults to false.LoopBreaker defaults to false.quota/quotamcp/config.go:77
OnCallfunc(ctx context.Context, info CallInfo)OnCall observes each metered call after it ends; optional. It never sees arguments or results.OnCall observes each metered call after it ends; optional.quota/quotamcp/config.go:80
OnMeteringErrorfunc(ctx context.Context, failure MeteringFailure)OnMeteringError observes each eligible metered tools/call that obtains no allow/deny decision, independently of OnError's once-per-plan-set reports. Other methods, malformed pass-through requests and exempt tools are excluded. It runs synchronously and must support concurrent calls; no context is retained. OnMeteringError is optional; nil disables the callback.OnMeteringError is optional; nil disables the callback.quota/quotamcp/config.go:86
OnErrorfunc(ctx context.Context, c Caller, err error)OnError receives callback errors, *quota.RequestError, settlement failures and plan sets that break a policy; optional. Store failures also reach quota.Hooks.OnStoreError.OnError receives callback errors, *quota.RequestError, settlement failures and plan sets that break a policy; optional.quota/quotamcp/config.go:90
Functions from package source
TypeSource
func (c MiddlewareConfig) ToMiddleware() (mcp.Middleware, error)quota/quotamcp/middleware.go:47

Import echo.labstack.com/pro/quota/quotamcp.

quotamcp.Policy · quota/quotamcp/config.go:94 · echo.labstack.com/[email protected]

Policy is one tool's metering policy.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
Attemptquota.CostAttempt is charged on every admitted call and never refunded by quotamcp, so rate limits and the loop breaker see every attempt. Nil means {"requests": 1}; an empty non-nil Attempt charges no attempt meter.Nil means {"requests": 1}; an empty non-nil Attempt charges no attempt meter.quota/quotamcp/config.go:98
Costquota.CostCost holds the billable meters, disjoint from Attempt. Attempt-counted tools charge it when the request is allowed. Settled tools reserve it as an upper bound and settle it with Charge; it is the only part quotamcp ever refunds. Cost is optional; nil has no billable work meters.Cost is optional; nil has no billable work meters.quota/quotamcp/config.go:103
SettleboolSettle reserves Attempt plus Cost and settles Cost with the actual. Settle defaults to false, charging Cost when the request is allowed.Settle defaults to false, charging Cost when the request is allowed.quota/quotamcp/config.go:106
ChargeFirstboolChargeFirst declares that the settled tool calls Charge(ctx, nil) or Charge with an amount before any billable work. When a failed call records no Charge, quotamcp assumes it never reached the handler and refunds Cost. A successful result without Charge breaks this declaration: quota keeps the reservation and reports the error to OnError.ChargeFirst declares that the settled tool calls Charge(ctx, nil) or Charge with an amount before any billable work.quota/quotamcp/config.go:111
ExemptboolExempt tools are never metered; they take no Attempt or Cost. Exempt defaults to false.Exempt defaults to false.quota/quotamcp/config.go:114

Import echo.labstack.com/pro/quota/quotaotel.

quotaotel.LifecycleConfig · quota/quotaotel/lifecycle.go:20 · echo.labstack.com/[email protected]

LifecycleConfig configures bounded call counters. Names are validated and copied. With the zero value all names map to _other.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
NamesNameAllowlistNames at zero maps all plan, limit and meter names to _other.Names at zero maps all plan, limit and meter names to _other.quota/quotaotel/lifecycle.go:22
Functions from package source
TypeSource
func NewLifecycle(mp metric.MeterProvider, cfg LifecycleConfig) (*Lifecycle, error)quota/quotaotel/lifecycle.go:35

Import echo.labstack.com/pro/quota/quotaotel.

quotaotel.TraceConfig · quota/quotaotel/tracing.go:35 · echo.labstack.com/[email protected]

TraceConfig configures synchronous span events. Its zero value is usable; disclosure and status changes are off. Callbacks and Logger remain caller-owned and must support concurrent calls and return promptly. No context is retained.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
NamesNameAllowlistNames is validated and copied; zero normalizes names to _other.Names is validated and copied; zero normalizes names to _other.quota/quotaotel/tracing.go:37
Identityfunc(quota.Identity) []attribute.KeyValueIdentity optionally returns attributes to include in traces. Nil discloses none. At most four candidates are checked. Only namespaced scalar attributes outside quota.*, error.*, gen_ai.* and mcp.* are kept. Keys are at most 64 bytes; string values are at most 128 bytes. Duplicate keys are dropped. Prefer a keyed digest. It remains linkable personal data and does not anonymize the caller.Identity optionally returns attributes to include in traces. Nil discloses none.quota/quotaotel/tracing.go:43
RemainingboolRemaining discloses coarse usage per subject, even without caller attributes. Remaining defaults to false.Remaining defaults to false.quota/quotaotel/tracing.go:46
MarkErrorsboolMarkErrors sets Error status only when an unavailable store causes a request to be rejected. MarkErrors defaults to false.MarkErrors defaults to false.quota/quotaotel/tracing.go:49
MaxEventAttrsintMaxEventAttrs includes the dropped marker: zero selects 16; otherwise 1–32.MaxEventAttrs includes the dropped marker: zero selects 16; otherwise 1–32.quota/quotaotel/tracing.go:51
FailuresFailureSinkFailures optionally counts recovered panics; nil does not count failures.Failures optionally counts recovered panics; nil does not count failures.quota/quotaotel/tracing.go:53
Logger*slog.LoggerLogger optionally receives fixed diagnostics, at most once per minute per constructed hook. Recovered values, caller data and error text are never logged.Logger optionally receives fixed diagnostics, at most once per minute per constructed hook.quota/quotaotel/tracing.go:56

Import echo.labstack.com/pro/quota/quotaprom.

quotaprom.LifecycleConfig · quota/quotaprom/lifecycle.go:23 · echo.labstack.com/[email protected]

LifecycleConfig configures bounded call counters. Names are validated and copied. With the zero value all names map to _other.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
NamesNameAllowlistNames at zero maps all plan, limit and meter names to _other.Names at zero maps all plan, limit and meter names to _other.quota/quotaprom/lifecycle.go:25
Functions from package source
TypeSource
func NewLifecycle(reg prometheus.Registerer, cfg LifecycleConfig) (*Lifecycle, error)quota/quotaprom/lifecycle.go:58

Import echo.labstack.com/pro/quota/quotastripe.

quotastripe.Config · quota/quotastripe/config.go:39 · echo.labstack.com/[email protected]

Config selects one immutable namespace and state history within a Stripe account. New copies maps and slices; the application owns Client, Store and callbacks. Callbacks must be safe for concurrent use and honor their bounded contexts.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
NamespacestringNamespace is required and identifies one account's immutable state history. The event index preserves the first customer and meter mapping across replay.Namespace is required and identifies one account's immutable state history.quota/quotastripe/config.go:42
StoreStoreStore is required, concurrency safe, and caller-owned.Store is required, concurrency safe, and caller-owned.quota/quotastripe/config.go:44
Client*http.ClientClient is required and caller-owned. An owned copy refuses redirects. Any RoundTripper is supported behind an HTTPS wrapper.Client is required and caller-owned.quota/quotastripe/config.go:47
APIKeyfunc(context.Context) (string, error)APIKey is required and supplies a key under a request deadline. One callback runs at a time; concurrent callers wait within their own bounded contexts. Keys are cached only in memory and never logged. Dispatch resolves or reuses a validated key before claiming work. A failure before claiming writes nothing, reports OnError with operation "dispatch", and pauses dispatch with escalating backoff.APIKey is required and supplies a key under a request deadline.quota/quotastripe/config.go:53
APIKeyTTLtime.DurationAPIKeyTTL defaults to one minute; require 1 second–15 minutes. A validated key is shared by workers and reads for this duration after resolution. Expiry, 401/403, validation failure and Run start clear it. Shorter TTLs reduce key memory residency and rotation delay but increase callback traffic. In-flight requests may finish with their admitted key.APIKeyTTL defaults to one minute; require 1 second–15 minutes.quota/quotastripe/config.go:59
Metersmap[string]MeterMeters contains 1–256 source-meter mappings; New takes a private copy. Meters is required; configure 1–256 mappings.Meters is required; configure 1–256 mappings.quota/quotastripe/config.go:62
Ignore[]stringIgnore contains at most 256 pure ignored source meters; default empty.Ignore contains at most 256 pure ignored source meters; default empty.quota/quotastripe/config.go:64
Customerfunc(context.Context, quota.ConsumptionEvent) (string, error)Customer is required. Its first event-specific result is durably indexed. Return ErrSkip to skip the event permanently. Any other error pauses export and retries.Customer is required.quota/quotastripe/config.go:67
Drainedfunc(context.Context) (bool, error)Drained reports whether final source usage through the chosen cutoff has arrived. Nil leaves source completeness unknown.Nil leaves source completeness unknown.quota/quotastripe/config.go:70
Windowtime.DurationWindow defaults to one minute; other nonzero grids are rejected.Window defaults to one minute; other nonzero grids are rejected.quota/quotastripe/config.go:72
Latenesstime.DurationLateness defaults to two minutes before automatic sealing. Nonzero values must be positive.Lateness defaults to two minutes before automatic sealing. Nonzero values must be positive.quota/quotastripe/config.go:74
ResendWithintime.DurationResendWithin defaults to 12 hours from the persisted first send intent; require RequestTimeout + 5m < ResendWithin < 23h55m.ResendWithin defaults to 12 hours from the persisted first send intent; require RequestTimeout + 5m < ResendWithin < 23h55m.quota/quotastripe/config.go:77
DedupeRetentiontime.DurationDedupeRetention defaults to 72 hours after window end; unresolved work pins it. Valid range 1 minute–10 years; it must match StoreConfig.DedupeRetention defaults to 72 hours after window end; unresolved work pins it.quota/quotastripe/config.go:80
DecisionRetentiontime.DurationDecisionRetention defaults to 35 days; valid range 1 minute–35 days. It must match StoreConfig.DecisionRetention defaults to 35 days; valid range 1 minute–35 days.quota/quotastripe/config.go:83
ReceiptRetentiontime.DurationReceiptRetention defaults to 400 days; MaxHistory can shorten actual coverage. Valid range 1 minute–10 years; it must match StoreConfig.ReceiptRetention defaults to 400 days; MaxHistory can shorten actual coverage.quota/quotastripe/config.go:86
LeaseTTLtime.DurationLeaseTTL defaults to two minutes; require >=3*RequestTimeout and <=24 hours.LeaseTTL defaults to two minutes; require >=3*RequestTimeout and <=24 hours.quota/quotastripe/config.go:88
BacklogAlarmtime.DurationBacklogAlarm defaults to 30 minutes for OnBacklog.BacklogAlarm defaults to 30 minutes for OnBacklog.quota/quotastripe/config.go:90
SummaryLagtime.DurationSummaryLag defaults to 15 minutes and must be positive. It is a heuristic, not a processing SLA.SummaryLag defaults to 15 minutes and must be positive.quota/quotastripe/config.go:92
RequestTimeouttime.DurationRequestTimeout defaults to 30 seconds; require 0 < timeout <=5 minutes.RequestTimeout defaults to 30 seconds; require 0 < timeout <=5 minutes.quota/quotastripe/config.go:94
RatePerSecondintRatePerSecond defaults to 20 for each shared POST/read budget; maximum 1000.RatePerSecond defaults to 20 for each shared POST/read budget; maximum 1000.quota/quotastripe/config.go:96
BurstintBurst defaults to one; maximum 1000 per budget.Burst defaults to one; maximum 1000 per budget.quota/quotastripe/config.go:98
WorkersintWorkers defaults to eight concurrent group workers; require 1–64. Each group has at most one local request in flight. All workers share rate budgets and the account authentication pause. Run cancels and joins them.Workers defaults to eight concurrent group workers; require 1–64.quota/quotastripe/config.go:102
MaxAttemptsintMaxAttempts defaults to 50; require 1–1000. Auth responses do not count.MaxAttempts defaults to 50; require 1–1000.quota/quotastripe/config.go:104
MaxDedupeEventsintMaxDedupeEvents defaults to 100000 per billed group, matching StoreConfig. Nonzero overrides must be 1–1000000 and must match StoreConfig.MaxDedupeEvents defaults to 100000 per billed group, matching StoreConfig. Nonzero overrides must be 1–1000000 and must match StoreConfig.quota/quotastripe/config.go:107
MaxDecisionsintMaxDecisions defaults to 100000 per terminal/counter shard, matching StoreConfig. Nonzero overrides must be 1–1000000 and must match StoreConfig.MaxDecisions defaults to 100000 per terminal/counter shard, matching StoreConfig. Nonzero overrides must be 1–1000000 and must match StoreConfig.quota/quotastripe/config.go:110
MaxOpenGroupsintMaxOpenGroups defaults to 10000 retained groups, including internal shards. Redis group counting is approximate across slots; matching StoreConfig is required. Nonzero overrides must be 1–1000000 and must match StoreConfig.MaxOpenGroups defaults to 10000 retained groups, including internal shards. Redis group counting is approximate across slots; matching StoreConfig is required. Nonzero overrides must be 1–1000000 and must match StoreConfig.quota/quotastripe/config.go:114
MaxUnsentBatchesintMaxUnsentBatches defaults to 10000 open/sealed/sending/uncertain/quarantined records per group, matching StoreConfig.MaxBatches. Sent receipts are excluded. Nonzero overrides must be 1–1000000 and must match StoreConfig.MaxUnsentBatches defaults to 10000 open/sealed/sending/uncertain/quarantined records per group, matching StoreConfig.MaxBatches. Nonzero overrides must be 1–1000000 and must match StoreConfig.quota/quotastripe/config.go:118
MaxQuarantinedintMaxQuarantined defaults to 10000 per group, matching StoreConfig. Nonzero overrides must be 1–1000000 and must match StoreConfig.MaxQuarantined defaults to 10000 per group, matching StoreConfig. Nonzero overrides must be 1–1000000 and must match StoreConfig.quota/quotastripe/config.go:121
Logger*slog.LoggerLogger is optional and caller-owned; default silence. Logs use fixed fields, bounded response classifications and only the last four customer characters.Logger is optional and caller-owned; default silence.quota/quotastripe/config.go:124
OnErrorfunc(context.Context, string, error)OnError is optional and may run concurrently; it must be concurrency safe, honor its bounded context and not block.OnError is optional and may run concurrently; it must be concurrency safe, honor its bounded context and not block.quota/quotastripe/config.go:127
OnBacklogfunc(context.Context, time.Duration)OnBacklog is optional; it must honor its bounded context and not block.OnBacklog is optional; it must honor its bounded context and not block.quota/quotastripe/config.go:129
Functions from package source
TypeSource
func New(cfg Config) (*Exporter, error)quota/quotastripe/config.go:134

Import echo.labstack.com/pro/quota/quotastripe.

quotastripe.StoreConfig · quota/quotastripe/store_config.go:19 · echo.labstack.com/[email protected]

StoreConfig bounds authoritative state. Zero fields select finite defaults. Prefix is a physical Redis prefix; Namespace remains part of the normalized group digest. Per-group caps are exact; Redis MaxGroups is approximate across cluster slots. Retained groups include persistent sequence/fence tombstones and never expire. Every nonzero capacity must be in [1, 2^30]. DedupeRetention and ReceiptRetention must be 1 minute–10 years. Constructors copy settings and retain the optional Clock callback.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
PrefixstringPrefix defaults to quotastripe; use <=32 lowercase letters, digits or underscores. An optional namespace: prefix accepts a namespace of up to 32 lowercase letters, digits, underscores or hyphens (for example myapp:prod).Prefix defaults to quotastripe; use <=32 lowercase letters, digits or underscores. An optional namespace: prefix accepts a namespace of up to 32 lowercase letters, digits, underscores or hyphens (for example myapp:prod).quota/quotastripe/store_config.go:23
Clockfunc() time.TimeClock is an optional concurrency-safe clock for isolated tests; default store time.Clock is an optional concurrency-safe clock for isolated tests; default store time.quota/quotastripe/store_config.go:25
DedupeRetentiontime.DurationDedupeRetention defaults to 72 hours, measured strictly after window end.DedupeRetention defaults to 72 hours, measured strictly after window end.quota/quotastripe/store_config.go:27
DecisionRetentiontime.DurationDecisionRetention defaults to 35 days; require one minute through 35 days.DecisionRetention defaults to 35 days; require one minute through 35 days.quota/quotastripe/store_config.go:29
ReceiptRetentiontime.DurationReceiptRetention defaults to 400 days; history capacity may evict sooner.ReceiptRetention defaults to 400 days; history capacity may evict sooner.quota/quotastripe/store_config.go:31
MaxDedupeEventsintMaxDedupeEvents defaults to 100000 per billed group. Index shards allow MaxDedupeEvents+MaxDecisions entries, additionally limited by MaxBytes.MaxDedupeEvents defaults to 100000 per billed group.quota/quotastripe/store_config.go:34
MaxDecisionsintMaxDecisions defaults to 100000 per terminal shard or daily-counter shard.MaxDecisions defaults to 100000 per terminal shard or daily-counter shard.quota/quotastripe/store_config.go:36
MaxGroupsintMaxGroups defaults to 10000, including internal shards and permanent tombstones. It is exact per MemoryStore and approximate per namespace across Redis slots.MaxGroups defaults to 10000, including internal shards and permanent tombstones.quota/quotastripe/store_config.go:39
MaxOpenWindowsintMaxOpenWindows defaults to 1000 per group.MaxOpenWindows defaults to 1000 per group.quota/quotastripe/store_config.go:41
MaxBatchesintMaxBatches defaults to 10000 unresolved records per group, including open work.MaxBatches defaults to 10000 unresolved records per group, including open work.quota/quotastripe/store_config.go:43
MaxQuarantinedintMaxQuarantined defaults to 10000 per group; quarantined input never expires.MaxQuarantined defaults to 10000 per group; quarantined input never expires.quota/quotastripe/store_config.go:45
MaxHistoryintMaxHistory defaults to 10000 sent receipts per group in companion storage. Oldest-first eviction advances CoverageLostBefore and never removes unresolved work.MaxHistory defaults to 10000 sent receipts per group in companion storage.quota/quotastripe/store_config.go:48
MaxReservationsintMaxReservations defaults to 1000 per group. It caps saved Capture replies (at most one minute) and persistent FlushOnce snapshots. Capture saves the state used for a flush; FlushOnce snapshots survive retries. The same limit caps persistent FlushOnce requests in the namespace slot. Persistent records are never evicted; a full registry rejects new request IDs. MaxBytes also applies. Seal creates no reply receipt.MaxReservations defaults to 1000 per group.quota/quotastripe/store_config.go:54
MaxBytesintMaxBytes defaults to 32 MiB for the active group record. It excludes sent receipts and durable flush receipts, which use companion storage. Each flush receipt is bounded by 32 * MaxBytes * (registered groups + 1). MaxReservations bounds the number of receipts. Namespace scheduling leases have a separate 2 KiB allowance, so a full flush registry can restart.MaxBytes defaults to 32 MiB for the active group record.quota/quotastripe/store_config.go:60
Functions from package source
TypeSource
func NewMemoryStore(cfg StoreConfig) (*MemoryStore, error)quota/quotastripe/memory.go:28
func NewRedisStore(client redis.UniversalClient, cfg StoreConfig) (*RedisStore, error)quota/quotastripe/redis.go:109

Import echo.labstack.com/pro/quota/quotastripe/stripeadmin.

stripeadmin.Config · quota/quotastripe/stripeadmin/panel.go:36 · echo.labstack.com/[email protected]

Config selects the caller-owned status reader. Status and optional readers are retained for the panel lifetime, never closed; all must be concurrency safe and honor cancellation.

Fields from package source
FieldTypeDescriptionDefaults / requirementsSource
StatusStatusReaderStatus is required, retained and caller-owned; it must honor ctx and be concurrency safe.Status is required, retained and caller-owned; it must honor ctx and be concurrency safe.quota/quotastripe/stripeadmin/panel.go:39
InspectionInspectionReaderInspection enables bounded shared-store diagnostic views. Nil omits them.Nil omits them.quota/quotastripe/stripeadmin/panel.go:41
ReconcileReconcileReaderReconcile enables a probe that compares exported totals with Stripe usage. Nil omits the action.Nil omits the action.quota/quotastripe/stripeadmin/panel.go:44
FlushFlushRunnerFlush enables an action that seals and dispatches eligible usage through the local dispatcher. The request is saved durably for retries. Nil omits the action.Nil omits the action.quota/quotastripe/stripeadmin/panel.go:47
Budgetquotastripe.InspectionBudgetBudget bounds inspection; zero uses quotastripe defaults.Budget bounds inspection; zero uses quotastripe defaults.quota/quotastripe/stripeadmin/panel.go:49
StripePagesintStripePages defaults to 10 and must be 1–100. Shared across Probe retries.StripePages defaults to 10 and must be 1–100.quota/quotastripe/stripeadmin/panel.go:51
IDstringID defaults to stripe; use 1–32 lowercase ASCII letters, digits or hyphens, starting with a letter, excluding api and assets.ID defaults to stripe; use 1–32 lowercase ASCII letters, digits or hyphens, starting with a letter, excluding api and assets.quota/quotastripe/stripeadmin/panel.go:54
BacklogAlarmtime.DurationBacklogAlarm is a display threshold; defaults to 30m, nonzero values must be positive.BacklogAlarm is a display threshold; defaults to 30m, nonzero values must be positive.quota/quotastripe/stripeadmin/panel.go:57
Nowfunc() time.TimeNow is retained and must be concurrency safe; nil uses time.Now.Now is retained and must be concurrency safe; nil uses time.Now.quota/quotastripe/stripeadmin/panel.go:59
Functions from package source
TypeSource
func New(cfg Config) (*Panel, error)quota/quotastripe/stripeadmin/panel.go:67
SettingDefault or limit
Plan.Limits1–16
LimitInfo.ID / LimitInfo.Meter[a-z0-9][a-z0-9_]{0,31}
Limit.Burst()Equals the refill amount unless set
Limit.Lease()Five minutes by default
Identity / operation stringsAt most 256 bytes each
Config.StoreTimeout25 ms by default; caller cancellation can end it sooner
Config.DenyCacheOff by default; at most ten seconds and never longer than the retry delay

Call Limiter.Close before closing its store or Redis client.

quota.NewTopK(k) returns (*quota.TopK, error) and rejects k outside 1..1000 with a *quota.ConfigError. quota.MustNewTopK(k) panics instead, for fixed configuration.

Package explanation · Task guide · Problem catalog