Designing and Building an In-Memory RESTful Q&A Service
System DesignModel answerLast updated
Architect and implement a minimal Q&A web service with HTTP endpoints for question creation, retrieval, and search, including pagination and data validation.
You are tasked with building a lightweight REST service implementing the core capabilities of a Stack Overflow-style Question and Answer platform.
Requirements
-
API Endpoints:
- Create Question: Accepts a title and detailed content body, with optional fields for user-defined tags and author identifier.
- Search/Query Questions: Allows searching by text contained within the title or body, and optionally filtering by tags.
- Get Question by ID: Fetches the complete metadata of a single question using its unique integer identifier.
-
Design Expectations:
- Define concrete choices for data persistence (e.g., an in-memory repository abstracted behind a repository interface).
- Implement pagination and ordering rules for search queries.
- Include validation for edge cases (e.g., empty fields, invalid query parameters, missing resources).
- Ensure safety under concurrent read and write operations.
Provide an architectural breakdown of the contract, a Discussion of trade-offs, and a complete code implementation.
Hints
Hint 1
Abstract your storage mechanism behind a repository interface or class so that an in-memory dictionary can easily be swapped with a relational database later.
Hint 2
Consider how tags are stored and matched. Standardizing tags to lowercase and stripping whitespace upon ingestion simplifies filtering logic.
Hint 3
Ensure read/write operations against shared memory structures are guarded with locks or thread-safe primitives to handle concurrent API requests safely.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. API Contract & Architectural Choices
Endpoints Specification
| Verb | Path | Success Code | Error Codes | Description |
|---|---|---|---|---|
POST | /questions | 201 Created | 422 Unprocessable Entity | Creates a new question. Returns the created item and sets the Location header to /questions/{id}. |
GET | /questions | 200 OK | 422 Unprocessable Entity | Queries questions using optional parameters (q, tags, sort, limit, offset). Returns a paginated wrapper. |
GET | /questions/{id} | 200 OK | 404 Not Found, 422 Unprocessable Entity | Retrives details of a specific question by integer ID. |
Storage & Concurrency
For an interview context, an in-memory storage layer managed by a thread-safe repository class is ideal. Using an ordered hash table (such as a standard Python dictionary) where keys are auto-incrementing integer IDs allows $O(1)$ lookup by ID and natural chronological order matching insertion order.
All state updates (allocating auto-increment IDs and inserting items) are executed inside a lock (e.g., threading.Lock) to handle multithreaded web application workers safely.
Tag Normalization & Search Semantics
- Tag Normalization: Tags are converted to lowercase, stripped of whitespace, and deduplicated on creation.
- Tag Search Filtering: Filtering by tags uses AND logic (i.e., a question must possess all requested tags to match).
- Text Search: Keyword matching (
q) performs case-insensitive substring search across both thetitleandbodyfields usingcasefold().
Pagination & Ordering
- Parameters:
limit(default: 20, max: 100) andoffset(default: 0). - Response shape:
{ "items": [...], "total": 45, "limit": 20, "offset": 0 } - Sorting options:
newest(default) oroldest.
2. Implementation (Python & FastAPI)
Below is a complete, runnable service implementation using FastAPI and Pydantic v2:
from __future__ import annotations
import threading
from datetime import datetime, timezone
from typing import Literal
from fastapi import FastAPI, HTTPException, Path, Query, Response
from pydantic import BaseModel, Field, field_validator
# --- Data Models & Schemas ---
class QuestionCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=200)
body: str = Field(..., min_length=1, max_length=10000)
tags: list[str] = Field(default_factory=list, max_length=5)
author: str | None = Field(default=None, max_length=64)
@field_validator("title", "body")
@classmethod
def validate_not_blank(cls, value: str) -> str:
trimmed = value.strip()
if not trimmed:
raise ValueError("Field cannot be blank or contain only whitespace.")
return trimmed
@field_validator("tags")
@classmethod
def normalize_tags(cls, raw_tags: list[str]) -> list[str]:
cleaned_tags: list[str] = []
for tag in raw_tags:
normalized = tag.strip().lower()
if not normalized or len(normalized) > 32:
raise ValueError("Tags must be non-empty and at most 32 characters long.")
if normalized not in cleaned_tags:
cleaned_tags.append(normalized)
return cleaned_tags
class Question(BaseModel):
id: int
title: str
body: str
tags: list[str]
author: str | None
created_at: datetime
class QuestionPage(BaseModel):
items: list[Question]
total: int
limit: int
offset: int
# --- Storage Layer ---
class QuestionRepository:
"""In-memory data store with thread synchronization."""
def __init__(self) -> None:
self._lock = threading.Lock()
self._storage: dict[int, Question] = {}
self._current_id = 1
def create(self, payload: QuestionCreate) -> Question:
with self._lock:
question_id = self._current_id
self._current_id += 1
record = Question(
id=question_id,
created_at=datetime.now(timezone.utc),
**payload.model_dump(),
)
self._storage[question_id] = record
return record
def get_by_id(self, question_id: int) -> Question | None:
with self._lock:
return self._storage.get(question_id)
def search(
self,
query: str | None,
tags: list[str],
sort: Literal["newest", "oldest"],
limit: int,
offset: int,
) -> tuple[list[Question], int]:
with self._lock:
records = list(self._storage.values())
if sort == "newest":
records.reverse()
normalized_query = query.casefold() if query else None
required_tags = set(tags)
matches: list[Question] = []
for item in records:
# Check text query match
text_match = True
if normalized_query:
in_title = normalized_query in item.title.casefold()
in_body = normalized_query in item.body.casefold()
text_match = in_title or in_body
# Check tag filters (AND match)
tag_match = required_tags.issubset(set(item.tags))
if text_match and tag_match:
matches.append(item)
total_matches = len(matches)
sliced_results = matches[offset : offset + limit]
return sliced_results, total_matches
# --- Application Setup & Endpoints ---
repository = QuestionRepository()
app = FastAPI(title="Q&A REST API Service", version="1.0.0")
@app.post("/questions", status_code=201, response_model=Question)
def create_question(
payload: QuestionCreate, response: Response
) -> Question:
question = repository.create(payload)
response.headers["Location"] = f"/questions/{question.id}"
return question
@app.get("/questions", response_model=QuestionPage)
def search_questions(
q: str | None = Query(default=None, max_length=200),
tags: list[str] | None = Query(default=None),
sort: Literal["newest", "oldest"] = Query(default="newest"),
limit: int = Query(default=20, ge=1, le=100),
offset: int = Query(default=0, ge=0),
) -> QuestionPage:
cleaned_tags: list[str] = []
if tags:
for tag in tags:
for t in tag.split(","):
n = t.strip().lower()
if n:
cleaned_tags.append(n)
items, total = repository.search(
query=q,
tags=cleaned_tags,
sort=sort,
limit=limit,
offset=offset,
)
return QuestionPage(
items=items,
total=total,
limit=limit,
offset=offset,
)
@app.get("/questions/{id}", response_model=Question)
def get_question(
id: int = Path(..., ge=1, description="Question unique ID")
) -> Question:
question = repository.get_by_id(id)
if not question:
raise HTTPException(status_code=404, detail=f"Question with ID {id} not found.")
return question
3. Complexity & Scalability Analysis
- Create: $O(1)$ operations for dictionary insertion and counter increment.
- Get by ID: $O(1)$ hash table lookup.
- Search Query: $O(N \cdot L)$ worst-case time complexity, where $N$ is the total count of stored questions and $L$ is the max length of question text, due to substring evaluation across elements.
- Space Complexity: $O(N \cdot L)$ memory usage for in-memory question entities.
Production Scale Upgrades
- Full-Text Search Engine: Replace linear in-memory string scanning with a full-text search engine (such as Elasticsearch or PostgreSQL
tsvectorwith inverted indexes) to achieve sub-linear text search. - Tag Indexes: Maintain a dedicated tag-to-question ID inverted index mapping (
dict[str, set[int]]) to compute tag set intersections ($O(|Tag_A| \cap |Tag_B|)$) before fetching entity payloads. - Keyset Pagination (Cursor-based): Offset pagination suffers from $O(\text{offset})$ performance degrade at high offsets and item drift under concurrent inserts. Replace
offsetwith cursor pagination (WHERE id < last_seen_id ORDER BY id DESC LIMIT limit).