Problem
Batching multiple small queries into a single large query can be a useful optimization. Write a class QueryBatcher
that implements this functionality.
The constructor should accept two parameters:
- An asynchronous function
queryMultiple
which accepts an array of string keysinput
. It will resolve with an array of values that is the same length as the input array. Each index corresponds to the value associated withinput[i]
. You can assume the promise will never reject. - A throttle time in milliseconds
t
.
The class has a single method.
async getValue(key)
. Accepts a single string key and resolves with a single string value. The keys passed to this function should eventually get passed to thequeryMultiple
function.queryMultiple
should never be called consecutively withint
milliseconds. The first timegetValue
is called,queryMultiple
should immediately be called with that single key. If aftert
milliseconds,getValue
had been called again, all the passed keys should be passed toqueryMultiple
and ultimately returned. You can assume every key passed to this method is unique.
The following diagram illustrates how the throttling algorithm works. Each rectangle represents 100ms. The throttle time is 400ms.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
0 <= t <= 1000
0 <= calls.length <= 10
1 <= key.length <= 100
- All keys are unique
Solution
Method 1 – Throttled Batching with Timer
Intuition
To efficiently batch queries, we use a timer to collect keys within the throttle window. The first call is immediate, and subsequent calls within the window are batched and sent together after the throttle time.
Approach
- Store pending keys and their resolvers in a queue.
- On the first call, immediately call
queryMultiple
and resolve the promise. - For subsequent calls within
t
ms, queue the keys and set a timer if not already set. - When the timer fires, call
queryMultiple
with all queued keys and resolve their promises. - Ensure no two
queryMultiple
calls are withint
ms.
Code
|
|
Complexity
- ⏰ Time complexity:
O(1)
pergetValue
call, batching is handled by timer and queue. - 🧺 Space complexity:
O(n)
, where n is the number of queued keys in the throttle window.