Turning JSON Point Data into Lines via a Third-Party Drawing Service
System DesignModel answerLast updated
Describe how to parse JSON point data, decide how points connect, build the drawing service's request, and recover safely from failures without creating duplicate drawings.
You are given a JSON file containing point data and access to a documented drawing service. The service takes a request body and renders lines or a map from it. Write a small program (or describe its design) that reads the points and asks the service to draw them connected together.
The following details are not given up front. They live in the service's documentation and in a sample request body, which you are expected to read before deciding anything:
- the service's endpoint, authentication method and request schema
- the coordinate reference system (plain Cartesian plane versus latitude/longitude)
- the rules for which points get connected
Walk through your approach to:
- Validating and interpreting the JSON input.
- Deciding how points are connected: input order, grouped paths, or explicit edges. Also decide whether a path closes back on its first point.
- Building the request body from the documented schema.
- Handling failures, including which ones are retried and how you avoid drawing the same thing twice.
- Confirming that the finished drawing is actually correct.
State which questions you would resolve from the documentation and which you would ask the interviewer.
Hints
Hint 1
Before writing any code, list the unknowns: coordinate order and units, connection rule, closed or open shape, and request schema. Take each answer from the docs and sample body, not from assumption.
Hint 2
Keep three layers apart: a validated internal model (points and segments), an adapter that converts it to the service's schema, and a client that handles transport, auth and retries. Then a schema change only touches the adapter.
Hint 3
Classify failures: invalid input and 4xx errors are not retried, 429 and 5xx and timeouts are retried with backoff. For a non-idempotent create call, use an idempotency key or check for an existing drawing before resending.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
This is an integration task, so most of the quality comes from not guessing. I would split the program into four stages: parse and validate, interpret connectivity, adapt to the API contract, and send with safe recovery. Then I would verify the result.
1. Read the contract first
Open the documentation and the sample request body and copy down:
- endpoint, HTTP method, auth scheme (API key header, bearer token) and content type
- exact field names, nesting, required versus optional fields
- coordinate convention:
[x, y]versus[lat, lng]versus[lng, lat], units, and range limits - whether it takes one polyline per call, many paths, or individual segments
- response shape, including any returned drawing ID, and documented error codes
- rate limits and size limits (maximum points per request)
The classic bug is swapped axis order (lat/lng versus lng/lat). The sample body is the cheapest way to detect it: run the sample's own points through my adapter and confirm I reproduce it exactly.
2. Parse and validate input
- Parse the JSON, failing with a clear message on malformed syntax.
- Check structure: is it a flat list of points, a list of paths, or nodes plus edges?
- Each point must have numeric, finite values (reject
null, strings, NaN, missing fields). Check geographic ranges (lat in [-90, 90], lng in [-180, 180]) if applicable. - Decide what to do with edge cases: empty input (nothing to draw, exit cleanly), a single point (no segment, so either draw a marker if the API supports it or report it), and consecutive duplicate points (drop them, since zero-length segments can be rejected or render oddly).
- Fail early and report which record is bad, rather than sending a half-valid request.
3. Decide connectivity explicitly
Write the rule down instead of leaving it implicit:
| Input shape | Interpretation |
|---|---|
| Flat ordered list | One open polyline in input order |
| List of lists | One polyline per group |
| Nodes plus edge list | One segment per edge, looked up by ID |
Also decide on closure. A polygon closes from the last point to the first; a polyline does not. If the docs say polygons need the first point repeated at the end, the adapter does that, not the parser. If the intent is unclear, ask the interviewer. Internally I would hold a list of paths, each a list of validated points, which covers every case above.
4. Build the request (adapter)
A pure function to_request(paths) -> dict maps the internal model to the documented schema. Because it is pure, it is easy to unit test against the sample body. If the API limits points per call, chunk long paths, overlapping by one point so the segments stay joined.
5. Send with safe failure handling
| Failure | Action |
|---|---|
| Local validation error | Do not call the API; report it |
| 400/422 | Do not retry; log the response message, which usually names the offending field |
| 401/403 | Do not retry; fix credentials |
| 404 | Likely a wrong endpoint or resource; do not retry |
| 429 | Retry after the Retry-After header, otherwise exponential backoff |
| 5xx, timeout, connection reset | Retry with exponential backoff and jitter, capped at a few attempts (say 3 to 5, starting near 500 ms) |
Idempotency is the subtle part. If a create call times out, the drawing may or may not exist. Options, in order of preference:
- Send a client-generated idempotency key if the API supports one.
- Make the request deterministic (for example a name derived from a hash of the input) and query for an existing drawing before retrying.
- If neither exists, retry only reads and treat an ambiguous write failure as "unknown": check state, then decide, rather than blindly resending.
Set explicit timeouts on every call, and never log secrets.
6. Verify the outcome
A 200 response does not prove the picture is right. I would check the returned ID or fetch the result, compare the number of segments or points against what I sent, and eyeball a render for a small known input (such as a square, which exposes axis swaps and missing closure immediately).
Example sketch
import json, time, requests
def load_paths(raw):
data = json.loads(raw)
paths = data if data and isinstance(data[0], list) else [data]
out = []
for p in paths:
pts = []
for pt in p:
x, y = float(pt["x"]), float(pt["y"]) # field names from docs
if pts and pts[-1] == (x, y):
continue # drop duplicates
pts.append((x, y))
out.append(pts)
return out
def to_request(paths, closed=False):
return {"paths": [
{"points": [[x, y] for x, y in (p + p[:1] if closed else p)]}
for p in paths if len(p) >= 2]}
def send(body, url, headers, key):
headers = {**headers, "Idempotency-Key": key}
for attempt in range(4):
try:
r = requests.post(url, json=body, headers=headers, timeout=10)
if r.status_code < 300:
return r.json()
if r.status_code not in (429, 500, 502, 503, 504):
r.raise_for_status()
except (requests.Timeout, requests.ConnectionError):
pass
time.sleep(0.5 * 2 ** attempt)
raise RuntimeError("drawing request failed after retries")
Complexity is O(n) in the number of points for parsing and building the request; runtime is dominated by network latency.
Common mistakes
- Assuming
[lat, lng]versus[lng, lat]instead of confirming against the sample. - Silently closing or not closing a shape.
- Retrying every error, including 4xx, or retrying a create call with no duplicate protection.
- Treating HTTP 200 as proof the drawing is correct.
- Mixing parsing, schema mapping and networking in one function, which makes the code hard to test.