Repair Async Watch-List Add/Remove Endpoints
System DesignModel answerLast updated
Debug failing REST handlers that add and remove movies in a watch list, fixing check ordering, ID comparison, persistence timing, and status codes.
Setting
You're handed a Movie DB service where signed-in users own watch lists: they can create, rename, and delete lists, and put movies into them or take them out. The routes and the schema for these operations are already in place, but the unit tests around the two movie-membership endpoints are red. This is a fix-the-bug exercise — read the existing handlers, find what's wrong, correct it. Don't redesign the service or move to a different API style.
The endpoints in question:
POST /watchlists/{watchListId}/movies— put a movie into the list. The movie's identifier travels in the request body.DELETE /watchlists/{watchListId}/movies/{movieId}— take a movie out of the list.
Behaviour the tests require
- A movie is added to a watch list that exists.
- A movie that is already in the list is added again.
- A movie is removed from a watch list that exists.
- Many movies are added in a row, then removed one at a time, with the list checked after each step.
- An add is attempted against a watch list that doesn't exist.
- A remove is attempted against a watch list that doesn't exist.
Contract and assumptions
404 Not Foundwhen the watch list — or, for adds, the movie — doesn't exist.409 Conflictwhen an add duplicates a movie already in the list.- A successful add answers
201 Createdor200 OK; a successful remove answers200 OKor204 No Content. - The list holds a collection of movie identifiers, and those identifiers may be object/reference types, not plain strings.
- Persistence is asynchronous: work isn't durable until the save resolves, and handlers must not answer before that.
- Where the contract leaves a choice of status code, adopt whatever the currently passing tests and neighbouring handlers already do. Don't introduce a new style mid-file.
Worth confirming before you start
- Are IDs strings or object/reference values, and what counts as "the same" identifier?
- Which success codes do the surrounding tests expect on add and on remove?
- Does an add require the movie to exist in the database, or only that the identifier is well-formed?
- On remove, when the list exists but the movie isn't a member, is that a
404or a benign no-op? - Are in-memory changes persisted automatically, or must every handler save explicitly?
- Should any of this be idempotent, or must a repeat operation raise an error?
Deliverables
- Add path — make scenarios 1, 2, and 5 pass. Settle the order of checks, the status each failure produces, and what a successful add returns after the write lands.
- Remove path — make scenarios 3 and 6 pass. Say which checks are shared with add, which are specific to removal, how the deletion becomes durable, and how a missing list differs from a non-member movie.
- Sequential consistency — make scenario 4 pass: interleaved adds and removals must leave the list in the right state at every observed point.
Hints
Hint 1
A handler that writes a 404 but keeps going will either answer twice ('headers already sent') or mutate a list it never found. Every failure branch has to return immediately.
Hint 2
If IDs are objects, `===`, `includes`, and `indexOf` compare references and always miss. The classic symptom is `splice(indexOf(id), 1)` returning -1 and quietly deleting the last element instead of the target.
Hint 3
An un-awaited `save()` means the test's next read sees stale data. And on remove, `filter` hands you a new array — if you don't assign it back, nothing actually changed.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Repairing the Watch-List Add/Remove Handlers
Diagnosing the failures
The routes and schema are not the problem. Four recurring bugs explain every red test:
- Checks that don't short-circuit. The handler writes
404and then continues, so it either attempts a second response or touches a list that was never loaded. - Reference equality on identifiers. Movie IDs are object/reference values, so
includes,indexOf, and===never match an equivalent-but-distinct object. Duplicates get through (scenario 2) and removals can't find their target (scenario 3). - The removal result thrown away or aimed at the wrong field.
filterreturns a brand-new array that nobody assigns back; or the predicate comparesm.idwhen the collection holds bare IDs; orsplice(indexOf(id), 1)is called with-1and silently deletes the last element — which is exactly what breaks the sequential scenario 4. - Answering before the write lands.
save()is not awaited, so the test's subsequent read sees the old state.
The repair is one uniform shape per handler:
parse input → resource exists → membership rule → mutate → await save → respond once
and every failure branch ends with return.
Part 1 — Add (scenarios 1, 2, 5)
Do all validation up front, before touching the collection:
| Check | On failure |
|---|---|
| Watch list exists | 404 (scenario 5) |
| Movie exists in the DB | 404 |
| Movie not already in the list, compared by value | 409 (scenario 2) |
Only when all three pass: append the ID, await the save, and answer 201 with the updated list (use 200 if the existing tests expect it). The list is checked first because it is the resource named in the URL — the remaining checks are meaningless if it doesn't exist.
Part 2 — Remove (scenarios 3, 6)
One check is shared with add: the watch list must exist, otherwise 404 (scenario 6). What's specific to remove:
- No movie-exists lookup. What matters is membership in the list, not existence in the catalogue.
- You need an unambiguous "not there" signal. Filter by value, compare lengths before and after. If the length didn't move, nothing was removed — answer
404per the contract rather than pretending success. - Otherwise assign the filtered array back onto the list,
awaitthe save, and answer200(or204under the existing convention).
Part 3 — Sequential consistency (scenario 4)
This isn't a separate feature. It falls out once three properties hold: each add appends exactly one ID and persists it; each remove deletes exactly the matching ID and persists; and no code path wholesale-replaces the collection. The splice(-1, 1) failure mode is the usual culprit — every "removal" deletes the wrong movie and the list silently drifts away from what the test expects.
Reference implementation (Python, framework-agnostic)
from dataclasses import dataclass, field
from typing import Any, Optional
@dataclass
class Response:
status: int
body: Any = None
@dataclass
class WatchList:
id: Any
name: str
movies: list = field(default_factory=list)
def to_dict(self) -> dict:
return {"id": str(self.id), "name": self.name,
"movies": [str(m) for m in self.movies]}
def same_id(a: Any, b: Any) -> bool:
"""Value comparison, not object identity."""
return str(a) == str(b)
async def add_movie(repo, watchlist_id: Any, body: Optional[dict]) -> Response:
movie_id = (body or {}).get("movieId")
if movie_id is None:
return Response(400, {"error": "movieId is required"})
watchlist = await repo.find_watchlist(watchlist_id)
if watchlist is None:
return Response(404, {"error": "Watch list not found"})
if not await repo.movie_exists(movie_id):
return Response(404, {"error": "Movie not found"})
if any(same_id(m, movie_id) for m in watchlist.movies):
return Response(409, {"error": "Movie already in watch list"})
watchlist.movies.append(movie_id)
await repo.save(watchlist)
return Response(201, watchlist.to_dict())
async def remove_movie(repo, watchlist_id: Any, movie_id: Any) -> Response:
watchlist = await repo.find_watchlist(watchlist_id)
if watchlist is None:
return Response(404, {"error": "Watch list not found"})
before = len(watchlist.movies)
remaining = [m for m in watchlist.movies if not same_id(m, movie_id)]
if len(remaining) == before:
return Response(404, {"error": "Movie not in watch list"})
watchlist.movies = remaining
await repo.save(watchlist)
return Response(200, watchlist.to_dict())
class InMemoryRepo:
def __init__(self, watchlists: dict, movie_ids: set):
self._watchlists = watchlists
self._movies = {str(m) for m in movie_ids}
async def find_watchlist(self, wid):
wl = self._watchlists.get(str(wid))
return None if wl is None else WatchList(wl.id, wl.name, list(wl.movies))
async def movie_exists(self, mid) -> bool:
return str(mid) in self._movies
async def save(self, wl: WatchList) -> None:
self._watchlists[str(wl.id)] = WatchList(wl.id, wl.name, list(wl.movies))
The 400 for a missing movieId is a malformed-input guard; if the suite maps that case differently, match it.
Why this satisfies the tests
- One response per request, and nothing is mutated after a failed check.
- Value-based comparison finds duplicates and removal targets no matter which identifier type arrives.
- Removal drops only matching entries and writes the result back. Since adds refuse duplicates, at most one element goes — and never the last one by accident.
await saveprecedes the response, so any follow-up read observes the new state.
Cost
With n movies in the list: add is O(n) for the duplicate scan plus one read and one write, O(1) extra space; remove is O(n) time and O(n) space for the filtered array.
Edge cases to verify
- Missing watch list →
404on both operations, with no write attempted. - Unknown movie on add →
404. - Duplicate add →
409, list untouched. - Removing a non-member →
404, list untouched, last element intact. - The same logical ID arriving as a string in one call and an object in another → still matched.
- Removing the final member → list persists as empty, not as
nulland not repopulated.