The question gives few details, so state your reading first: decryptEncrypt(key, payload, callback) is asynchronous and calls back with the decrypted payload and a new key that the next call must use. That makes the calls dependent: two can't run at once, because the second doesn't know its key until the first finishes. So the class is a serial queue. decrypt(payload, callback) pushes the request and calls next(). next() does nothing if a call is in flight or the queue is empty; otherwise it takes the first request and calls decryptEncrypt with the current key. In that callback: store the new key, mark the class idle, hand the result to the caller's callback, and call next() again. Read the key when the request's turn comes, not when it was queued. The same thing as a promise chain is this.tail = this.tail.then(run).
Implement a Decryption class — focuses on managing async operations and a callback queue. The provided decryptEncrypt(key, payload, callback) generates a new key per call; your class must enqueue callbacks and process them in order as decryption completes. (The name is misleading — it's an async-operations question, not a security question.)
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Assumed here: the provided function calls back as callback(nextKey, result), and it is passed to the constructor with the first key. Requests wait in queue; busy says whether a call is in flight. next starts one call at a time, always with the latest key, and the completion handler saves the new key, delivers the result and starts the next request. The checks use a fake decryptEncrypt whose delay depends on the payload: a slow first request still finishes before a fast second one starts, and the keys used are 1, 2, 3. The finally keeps the queue moving if a caller's callback throws.
// decryptEncrypt(key, payload, callback) hands back the key for the NEXT call, so calls can't// overlap: each must wait for the one before it. Requests wait in a queue.class Decryption {constructor(initialKey, decryptEncrypt) {this.key = initialKey;this.decryptEncrypt = decryptEncrypt;this.queue = [];this.busy = false;}decrypt(payload, callback) {this.queue.push({ payload, callback });this.next();}next() {if (this.busy || this.queue.length === 0) return;this.busy = true;const { payload, callback } = this.queue.shift();this.decryptEncrypt(this.key, payload, (nextKey, result) => {this.key = nextKey;this.busy = false;try {callback(result);} finally {this.next(); // even if the caller's callback throws, the queue moves on}});}}
passes 8 checks run on every build, against the native method where there is one
- each call uses the key the previous call returned
- only one call is in flight at a time
- callbacks run in request order, even when a later one would be faster
- a request made later, while idle or busy, joins the same sequence
- a callback made from inside a callback is queued too
- a callback that throws doesn't stall the queue
- order holds when some calls answer synchronously and some later
- works when the provided function calls back synchronously
A promise chain is a queue: tail is the promise of everything requested so far, and each new call is attached with then, so it starts only when the previous one has settled. decrypt returns the promise for its own result and still accepts a callback. tail is stored with its rejection swallowed, so a call that throws rejects its own promise but doesn't break the chain, and since it never delivered a new key the next call reuses the current one.
// The same queue as a promise chain: each call is chained after the one before it, and// decrypt() returns a promise (a callback still works). A failed call doesn't block the rest.class Decryption {constructor(initialKey, decryptEncrypt) {this.key = initialKey;this.decryptEncrypt = decryptEncrypt;this.tail = Promise.resolve(); // settles when everything queued so far is done}decrypt(payload, callback) {const result = this.tail.then(() =>new Promise((resolve) => {// The key is read here, when this call's turn comes, not when decrypt() was called.this.decryptEncrypt(this.key, payload, (nextKey, text) => {this.key = nextKey;resolve(text);});}),);this.tail = result.catch(() => {}); // the chain itself never rejectsif (callback) result.then(callback, () => {});return result;}}
passes 6 checks run on every build, against the native method where there is one
- each call uses the key the previous call returned
- only one call is in flight at a time
- results arrive in request order, even when a later one would be faster
- a request made later joins the same sequence
- a call that throws rejects its own promise; the key is kept and the queue goes on
- a callback still works, alongside the promise
With a serial queue, one call that never calls back blocks every request behind it. A timer rejects that call after timeoutMs and lets the queue continue. A settled flag makes the first outcome the only one: a second callback, or a callback that arrives after the timeout, is ignored instead of overwriting the key. One thing a timeout can't fix: if the lost call did rotate the key on the other side, the stored key is now out of step, and the class would need a way to fetch a fresh one.
// Guards for a callback API you don't control: a call that never calls back would hang the// queue forever, and one that calls back twice would corrupt the key.class Decryption {constructor(initialKey, decryptEncrypt, { timeoutMs = 5000 } = {}) {this.key = initialKey;this.decryptEncrypt = decryptEncrypt;this.timeoutMs = timeoutMs;this.tail = Promise.resolve();this.pending = 0; // queued or running}decrypt(payload) {this.pending++;const result = this.tail.then(() => this.run(payload));this.tail = result.then(() => { this.pending--; },() => { this.pending--; },);return result;}run(payload) {return new Promise((resolve, reject) => {let settled = false;const timer = setTimeout(() => {settled = true;reject(new Error('decrypt timed out'));}, this.timeoutMs);const finish = (nextKey, text) => {if (settled) return; // a second callback, or one that arrives after the timeoutsettled = true;clearTimeout(timer);this.key = nextKey;resolve(text);};try {this.decryptEncrypt(this.key, payload, finish);} catch (error) {settled = true;clearTimeout(timer);reject(error);}});}}
passes 12 checks run on every build, against the native method where there is one
- each call uses the key the previous call returned
- only one call is in flight at a time
- results arrive in request order, even when a later one would be faster
- a request made later joins the same sequence
- a call that throws rejects its own promise; the key is kept and the queue goes on
- a call that never calls back times out, and the queue moves on
- a second callback from the same call is ignored
- a callback that arrives after the timeout is ignored
- no timer is left running after a call finishes or throws
- a call that throws and calls back later is still a failure
- pending goes back to zero after a failure too
- pending counts queued and running calls
Token refresh
A refresh token that changes on every use has this exact shape: each refresh needs the token the previous refresh returned, so concurrent requests must wait in line behind one refresh call.
Sequence numbers and nonces
APIs that require an increasing nonce or sequence number per request need the same serial queue: the value for request N+1 is only known after request N.
Web Locks
The platform version of 'one at a time': navigator.locks.request(name, callback) queues callbacks and runs them one after another, even across tabs.
Starting every request at once: they all use the first key, and all but one are wrong.
Capturing the key when the request is queued instead of when it starts.
Forgetting to start the next request after one finishes, so only the first ever runs.
Not clearing the busy flag when a call fails or its callback throws: the queue stalls for good.
Delivering results out of order by letting a later, faster call finish first.
Trusting the provided function to call back exactly once.
Why can't the requests run in parallel?
Each call's key comes from the previous call's result. That dependency forces a sequence; a concurrency limit above 1 would send several requests with the same, already used key.
How would you write it with async/await?
Promisify decryptEncrypt once, then decrypt is this.tail = this.tail.then(async () => { const [key, text] = await call(this.key, payload); this.key = key; return text; }). The chain is still what serialises it.
What should happen to queued requests after a failure?
It depends on whether the key is still valid. If the failed call didn't consume the key, carry on. If the key state is unknown, reject everything queued and re-establish a key first.
How would you cancel a queued request?
Keep the queue as an array of entries and remove the entry, or pass an AbortSignal and check it when the request's turn comes. A request already in flight can only be ignored, not undone.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#the_finally_block
- developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout
- developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API