Implement a one-shot event that queues callbacks until it fires

Quick Overview

Design a one-shot event where callbacks queue until the first fire, run in registration order when it fires, and run immediately once it has fired. It tests state machine modeling, queue handling, and how to keep registration and firing correct when threads race and callbacks re-enter.

Implement a one-shot event that queues callbacks until it fires

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

This is the sequential core of a concurrency interview question. Design a one-shot event that callbacks can register with. Each callback is represented by a distinct string `callback_id`, which stands in for a real callback function. The event can fire only once. Before it fires, a registered callback is queued and does not run yet. The first fire runs every queued callback in registration order and clears the queue. After the event has fired, a newly registered callback runs immediately, and any later fire does nothing. To make execution observable, both methods return the list of callback IDs executed by that call. No real functions, event payloads or threads are passed in. Lock scope, registration/fire races and re-entrant callbacks are left for the follow-up discussion, and checking the sequential behavior does not prove thread safety. Implement the class `OneShotEvent()` with these methods: - `register_callback(callback_id: str) -> list[str]`: if the event has not fired yet, queue `callback_id` and return `[]`. If it has already fired, run the callback right away and return `[callback_id]`. - `fire() -> list[str]`: on the first call, mark the event as fired, return all queued callback IDs in registration order, and clear the queue. Every later call returns `[]`. In the examples, the first input line lists the calls, the second line lists their arguments, and the output holds each call's return value (`null` for the constructor). Example 1: ```text Input: ["OneShotEvent", "register_callback", "register_callback", "fire", "register_callback", "fire"] [[], ["a"], ["b"], [], ["c"], []] Output: [null, [], [], ["a", "b"], ["c"], []] event = OneShotEvent() # not fired yet, queue: [] event.register_callback("a") # -> [] (queued, queue: [a]) event.register_callback("b") # -> [] (queued, queue: [a, b]) event.fire() # -> ["a", "b"] (runs queued IDs in registration order, queue cleared) event.register_callback("c") # -> ["c"] (already fired, runs immediately) event.fire() # -> [] (repeated fire does nothing) ``` Example 2: ```text Input: ["OneShotEvent", "fire", "register_callback", "fire"] [[], [], ["x"], []] Output: [null, [], ["x"], []] event = OneShotEvent() # not fired yet, queue: [] event.fire() # -> [] (first fire with an empty queue, event is now fired) event.register_callback("x") # -> ["x"] (already fired, runs immediately) event.fire() # -> [] (repeated fire does nothing) ``` ```hint State Write down the two states the event can be in and what each method does in each one. A first fire on an empty queue still moves the event to the second state. ``` ```hint Dispatch order Picture a real callback that registers another callback while `fire` is still running the queue. Decide what it should see, and order the steps inside `fire` to match. ``` ### Constraints & Assumptions - `1 <= len(callback_id) <= 20` - `callback_id` contains only English letters, digits, `-` and `_`. - All callback IDs within a single test case are distinct. - At most `1000` calls in total are made to `register_callback` and `fire`. ### Clarifying Questions to Ask - Does a fire with nothing queued count as the one allowed fire? - In the real version, if a queued callback raises, should the callbacks after it still run? - Must a callback registered after the fire wait for the queued callbacks to finish, or may it run as soon as it is registered? ### What a Strong Answer Covers - The two states and the behavior of each method in each state, including a first fire on an empty queue. - Registration order on the first fire, and a queue that is cleared so no callback runs twice. - Why the flag is set and the queue detached before any callback runs. - How the threaded version keeps check-and-enqueue and flip-and-swap atomic, and why callbacks run outside the lock. - The time and space cost of each method. ### Follow-up Questions - Make the event thread-safe. Which state goes under the lock, and how do you rule out a registration being lost or run twice when it races with `fire`? - Why should callbacks run outside the lock, and what happens if a callback calls `register_callback` or `fire` on the same event? - A queued callback throws an exception. What should happen to the callbacks after it, and to the caller of `fire`? - A callback registered just after the fire can run before the queued callbacks finish. When does that matter, and how would you prevent it?

Overview: Design a one-shot event where callbacks queue until the first fire, run in registration order when it fires, and run immediately once it has fired. It tests state machine modeling, queue handling, and how to keep registration and firing correct when threads race and callbacks re-enter.

PracHub logo
General
Nov 24, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

This is the sequential core of a concurrency interview question. Design a one-shot event that callbacks can register with. Each callback is represented by a distinct string callback_id, which stands in for a real callback function.

The event can fire only once. Before it fires, a registered callback is queued and does not run yet. The first fire runs every queued callback in registration order and clears the queue. After the event has fired, a newly registered callback runs immediately, and any later fire does nothing.

To make execution observable, both methods return the list of callback IDs executed by that call. No real functions, event payloads or threads are passed in. Lock scope, registration/fire races and re-entrant callbacks are left for the follow-up discussion, and checking the sequential behavior does not prove thread safety.

Implement the class OneShotEvent() with these methods:

  • register_callback(callback_id: str) -> list[str] : if the event has not fired yet, queue callback_id and return [] . If it has already fired, run the callback right away and return [callback_id] .
  • fire() -> list[str] : on the first call, mark the event as fired, return all queued callback IDs in registration order, and clear the queue. Every later call returns [] .

In the examples, the first input line lists the calls, the second line lists their arguments, and the output holds each call's return value (null for the constructor).

Example 1:

Input:
["OneShotEvent", "register_callback", "register_callback", "fire", "register_callback", "fire"]
[[], ["a"], ["b"], [], ["c"], []]

Output: [null, [], [], ["a", "b"], ["c"], []]

event = OneShotEvent()          # not fired yet, queue: []
event.register_callback("a")    # -> []          (queued, queue: [a])
event.register_callback("b")    # -> []          (queued, queue: [a, b])
event.fire()                    # -> ["a", "b"]  (runs queued IDs in registration order, queue cleared)
event.register_callback("c")    # -> ["c"]       (already fired, runs immediately)
event.fire()                    # -> []          (repeated fire does nothing)

Example 2:

Input:
["OneShotEvent", "fire", "register_callback", "fire"]
[[], [], ["x"], []]

Output: [null, [], ["x"], []]

event = OneShotEvent()          # not fired yet, queue: []
event.fire()                    # -> []      (first fire with an empty queue, event is now fired)
event.register_callback("x")    # -> ["x"]   (already fired, runs immediately)
event.fire()                    # -> []      (repeated fire does nothing)

Constraints & Assumptions

  • 1 <= len(callback_id) <= 20
  • callback_id contains only English letters, digits, - and _ .
  • All callback IDs within a single test case are distinct.
  • At most 1000 calls in total are made to register_callback and fire .

Clarifying Questions to Ask Guidance

  • Does a fire with nothing queued count as the one allowed fire?
  • In the real version, if a queued callback raises, should the callbacks after it still run?
  • Must a callback registered after the fire wait for the queued callbacks to finish, or may it run as soon as it is registered?

What a Strong Answer Covers Guidance

  • The two states and the behavior of each method in each state, including a first fire on an empty queue.
  • Registration order on the first fire, and a queue that is cleared so no callback runs twice.
  • Why the flag is set and the queue detached before any callback runs.
  • How the threaded version keeps check-and-enqueue and flip-and-swap atomic, and why callbacks run outside the lock.
  • The time and space cost of each method.

Follow-up Questions Guidance

  • Make the event thread-safe. Which state goes under the lock, and how do you rule out a registration being lost or run twice when it races with fire ?
  • Why should callbacks run outside the lock, and what happens if a callback calls register_callback or fire on the same event?
  • A queued callback throws an exception. What should happen to the callbacks after it, and to the caller of fire ?
  • A callback registered just after the fire can run before the queued callbacks finish. When does that matter, and how would you prevent it?