FastPrepConfigurable Per-Client Token Buckets

Configurable Per-Client Token Buckets

Snowflake logoSnowflake● HardFULLTIMEPHONE SCREEN
Learn

Problem statement

Simulate tiered per-client token-bucket rate limiting. The built-in default tier starts with capacity 1 and refill rate 1 token per second. Process commands in nondecreasing integer timestamp order:

  • CONFIG time tier capacity refill creates or replaces a tier. Before replacing an existing tier, refill every client currently assigned to it through time using the old rate, then clamp its tokens to the new capacity. A capacity increase does not grant extra tokens.
  • ASSIGN time client tier assigns a known tier and resets that client's bucket to the tier's full capacity at time. An unknown tier returns INVALID without changing state.
  • UNASSIGN time client assigns the client to default and resets its bucket to the current default capacity.
  • REQUEST time client cost creates an unseen client on default, refills through time, and returns ALLOW after spending cost tokens when enough exist; otherwise it returns REJECT.

Refill is elapsedSeconds * refill, capped at capacity. Return one result string per command; successful configuration and assignment commands return OK.

Function

simulateClientTokenBuckets(operations: String[]) → String[]

Examples

Example 1

operations = ["CONFIG 0 gold 5 2","ASSIGN 0 alice gold","REQUEST 0 alice 3","REQUEST 1 alice 3","REQUEST 1 alice 2","UNASSIGN 2 alice","REQUEST 2 alice 1"]return = ["OK","OK","ALLOW","ALLOW","REJECT","OK","ALLOW"]

Alice uses the gold bucket until unassignment resets her to the default tier.

Example 2

operations = ["REQUEST 0 bob 1","CONFIG 1 default 3 1","REQUEST 1 bob 3","REQUEST 3 bob 3"]return = ["ALLOW","OK","REJECT","ALLOW"]

Reconfiguration preserves Bob's refilled token balance rather than filling the larger bucket.

Constraints

  • 1 <= operations.length <= 10000
  • Timestamps are nonnegative, nondecreasing, and fit in signed 64-bit integers.
  • 1 <= capacity, refill, cost <= 10^9.
  • Tier and client names are nonempty alphanumeric strings.
  • All intermediate token arithmetic fits in signed 64-bit integers.

More Snowflake problems

See Snowflake hiring insights
public String[] simulateClientTokenBuckets(String[] operations) {
    // Write your code here.
}
operations["CONFIG 0 gold 5 2","ASSIGN 0 alice gold","REQUEST 0 alice 3","REQUEST 1 alice 3","REQUEST 1 alice 2","UNASSIGN 2 alice","REQUEST 2 alice 1"]
expected["OK", "OK", "ALLOW", "ALLOW", "REJECT", "OK", "ALLOW"]
Checking account…