✓ New endpoint GET /api/v1/puzzles/{puzzleId}/leaderboard is ready: 21 tests, validation, filtering, pagination, serialization and OpenAPI documentation.
#[ApiResource(operations: [
new Get(
uriTemplate: '/v1/puzzles/{puzzleId}/leaderboard',
provider: PuzzleLeaderboardResponseProvider::class,
parameters: [ /* filters — act 2 */ ],
),
])]
final class PuzzleLeaderboardResponse
{
public function __construct(
public string $puzzleId,
public int $total,
public bool $hasMore,
/** @var list<PuzzleLeaderboardEntryResponse> */
public array $entries,
) {}
}
→ one DTO = one response shape. no entity. no groups.
act 1 · easy part
DECISION 2
SCENARIOS, NOT CRUD
act 1 · easy part
WHAT THE USER ACTUALLY WANTS
CRUD
PATCH /competitions/42
{ "status": "published" }
SCENARIO
POST /competitions/42/publish
→ nobody has ever opened an app to update an entity
act 1 · easy part
DESIGN FROM THE SCREEN, NOT THE TABLE
the screenwhat the user wantsthe code
puzzle: Ravensburger 1000 ▾time: 45:12☑ first trySave my time
"add my solving time"
AddPuzzleSolvingTime↓handler
→ name the code after the click, not after the table
→ one command, 4 callers: web form · public API · AI agents · CLI import
act 1 · easy part
WHY NOT CRUD? · "I SOLVED IT!" THE CRUD WAY
# the first try of a puzzle (the client has to move the flag itself)
GET /puzzle_solving_times?player=me&puzzle=…&first_attempt=true
PATCH /puzzle_solving_times/{old} {"first_attempt": false}
POST /puzzle_solving_times {"first_attempt": true, "seconds": 2712, …}
DELETE /wish_list_items/{id} # solved it, so not on my wishlist any morePOST /notifications … # to my followers? private profile?
POST /player_badges … # for me? my 3 teammates too?
PATCH /puzzle_statistics/{id} … # the average time changed
→ 7 calls. 0 transactions. the rules live in the mobile app.
→ crash after call 2? your first try is gone. two phones? two first tries.
act 1 · easy part
"I SOLVED IT!" · THE SCENARIO WAY
POST /api/v1/me/solving-times
{ "puzzle_id": "…", "time": "45:12", "first_attempt": true }
6 RULES · ONE TRANSACTION
same key = same save · no accidental twin · the round must be public · one first try per puzzle (the flag moves) · under 100 pieces/min · teammates resolved
7 REACTIONS · AFTERWARDS
badges for every teammate · XP · puzzle statistics · time predictions · duplicate scan · notify followers (privacy-aware) · off the wishlist
→ 1 call. the rules live where every client has to pass.
src/MessageHandler/AddPuzzleSolvingTimeHandler.php · the PuzzleSolved event, 5 listeners
act 1 · easy part
DECISION 3
THE READ MODEL
ask the database the question the screen asks.
act 1 · easy part
PREDICT
GET /me/results for our top puzzler
2,327 results · 2,159 puzzles · about 2 MB of JSON
how many SQL queries would classic Doctrine CRUD fire?
?
act 1 · easy part
MEASURED · SAME DB, SAME DATA
Doctrine CRUD ████████████████████████████ 9,210 queries
9,559 entities in memory · in ONE request
read model ▏ 7 queries
0 entities · 108 ms, whole request
→ the REST-purist version: relations as links, the client does the joins. 4,400+ HTTP requests for one screen.
act 1 · easy part
N+1
N+1: walking to the box for every single piece
act 1 · easy part
PUTTING IT TOGETHER · THE LAYERS
HTTP · API Platformapplicationdomain · storage
READ
GET→Provider
Query→Result DTO
hand-written SQL
← Response DTO · no entity touched
WRITE
POST→Input ✓→Processor
Command→bus→Handler
Entity→Repository
← handler returns void · the response comes from the read side
→ HTTP lives in the first column only. the rest doesn't know it exists.
#[ApiResource(operations: [new Get(
uriTemplate: '/v1/me/collections',
security: "is_granted('ROLE_PAT') or is_granted('ROLE_OAUTH2_COLLECTIONS:READ')",
provider: MyCollectionsResponseProvider::class,
)])]
final class MyCollectionsResponse { public string $playerId; public int $count; public array $collections; }
// the provider: ask the read side, return the DTO
$collections = $this->getPlayerCollections->byPlayerId($playerId);
return new MyCollectionsResponse($playerId, count(…), array_map(…));
-- the query object: SQL straight into a DTO
SELECT id, name, description, visibility, … FROM collection WHERE player_id = :playerId
→ no entity. no hydration. the website uses the same query.
act 1 · end to end
END TO END · WRITE ① THE INPUT
src/Api/V1/CreateCollectionInput.php
#[ApiResource(operations: [
new Post(
uriTemplate: '/v1/me/collections',
security: "is_granted('ROLE_PAT') or is_granted('ROLE_OAUTH2_COLLECTIONS:WRITE')",
output: CollectionResponse::class,
processor: CreateCollectionProcessor::class,
),
])]
final class CreateCollectionInput
{
#[Assert\NotBlank] #[Assert\Length(max: 100)]
public string $name = '';
#[Assert\Length(max: 500)]
public ?string $description = null;
}
→ body validation on the input. invalid? a 422 before any of my code runs.
act 1 · end to end
END TO END · WRITE ② THE PROCESSOR
src/Api/V1/CreateCollectionProcessor.php
$playerId = $user->getPlayer()->id->toString();
if ($profile->activeMembership === false) {
throw new AccessDeniedHttpException('Active membership is required…');
}
$collectionId = Uuid::uuid7()->toString();
$this->messageBus->dispatch(new CreateCollection(
collectionId: $collectionId,
playerId: $playerId,
name: $data->name, …
));
return new CollectionResponse(collectionId: $collectionId, …);
→ the processor is an adapter. the command has no idea HTTP exists.
act 1 · end to end
END TO END · WRITE ③ COMMAND → HANDLER
src/MessageHandler/CreateCollectionHandler.php
public function __invoke(CreateCollection $message): void
{
$player = $this->playerRepository->get($message->playerId);
if ($this->collectionRepository->findByNameAndPlayer(…) !== null) {
throw new CollectionAlreadyExists(…);
}
$this->collectionRepository->save(new Collection(
id: Uuid::fromString($message->collectionId),
player: $player, name: $message->name, …
));
}
→ the same handler serves the website form, the API and the CLI
→ that was team A: the clean way. five classes for one write.
act 1 · end to end
TEAM B · THE PRAGMATIC WAY
Fantasy Academy · api/src/Message/Subscription/CreateCheckoutSession.php
#[Post(
uriTemplate: '/subscription/checkout',
output: CheckoutSessionResponse::class,
messenger: 'input',
)]
readonly final class CreateCheckoutSession implements UserAware
{
use WithUserId;
public function __construct(
#[Assert\Choice(['monthly', 'yearly'])]
public string $plan,
private ?Uuid $userId = null,
) {}
}
→ no processor. no mapping. the message is the resource.
→ the handler's return value becomes the response (API Platform reads the HandledStamp)
→ honest: hand-made. no Doctrine, so no Doctrine paginator.
act 2 · production
BODY VALIDATION · WHEN ATTRIBUTES AREN'T ENOUGH
src/Api/V1/CreateSolvingTimeInput.php
#[Assert\Regex('/^\d{1,2}:\d{2}(:\d{2})?$/', message: 'Time must be in format HH:MM:SS or MM:SS')]
public string $time = '';
#[Assert\Positive]
public ?int $piecesPlaced = null; // an unfinished competition result#[Assert\Callback]
public function validateTime(ExecutionContextInterface $context): void
{
if ($this->piecesPlaced === null && trim($this->time) === '') {
$context->buildViolation('This value should not be blank.')
->atPath('time')->addViolation();
}
}
→ rules across fields live on the input too. same 422, same violations format.
act 2 · production
THE LIMIT OF VALIDATION
SOME RULES CAN'T BE CHECKED AT THE DOOR
"one first try per puzzle" needs the database. and a race beats any form.
if ($message->firstAttempt) {
$firstTry = $this->firstTryAssessor->assess(…);
if ($firstTry->blocks($message->firstTryResolution)) {
throw new FirstTryAlreadyTaken($firstTry);
}
}
// src/Exceptions/FirstTryAlreadyTaken.php
final class FirstTryAlreadyTaken extends \Exception
→ no HTTP. no status code. just the business saying no.
act 2 · production
TRANSLATED AT THE EDGE
src/Api/V1/CreateSolvingTimeProcessor.php
try {
$this->messageBus->dispatch(new AddPuzzleSolvingTime(…));
} catch (HandlerFailedException $exception) {
if ($exception->getPrevious() instanceof FirstTryAlreadyTaken) {
throw FirstTryConflictResponse::from(…); // → 422 + a helpful detail
}
…
}
// src/Controller/PuzzleAddController.php: the SAME exception
if ($realException instanceof FirstTryAlreadyTaken) {
$form->addError(new FormError(…)); // → a red form error
}
→ one domain exception. two translations. each door speaks its own language.
act 2 · production
OPENAPI · DOCS THAT CAN'T LIE
src/Api/V1/CreateSolvingTimeInput.php
openapi: new OpenApiOperation(
description: 'Linking the time to an event (all optional): round_id …',
parameters: [new Parameter(name: 'Idempotency-Key', in: 'header', …)],
responses: [
'422' => new OpenApiResponse(description: 'Invalid input, a first attempt
already recorded, or an Idempotency-Key already used…'),
'404' => new OpenApiResponse(description: 'round_id, competition_id or
series_id is unknown… nothing is saved.'),
],
),
→ schemas come from the DTOs. the edge cases live next to the code that throws them.
act 2 · production
ONE CODEBASE · 3 KINDS OF CALLER
OAuth2 apps scopes → roles ─┐
personal tokens Authorization: Token msp_pat_… ─┼─▶ ApiUser ─▶ same commands
AI agents internal API, ~90 scenario endpoints ─┘
→ who you are is a firewall problem. what you do is a command.
→ scopes become roles. a whole path is closed even if an endpoint forgets.
act 2 · production
SECURITY ② WHAT MAY YOU DO?
// 1. the operation: is this token allowed here at all?
security: "is_granted('ROLE_PAT') or is_granted('ROLE_OAUTH2_COLLECTIONS:WRITE')",
// 2. the processor: the business rule → 403
if ($profile->activeMembership === false) {
throw new AccessDeniedHttpException('Active membership is required…');
}
// 3. the provider: be nice to the database → 429
if (!$this->apiPuzzleSearchLimiter->create($key)->consume()->isAccepted()) {
throw new TooManyRequestsHttpException($retryAfterSeconds, …);
}
→ token scope, business permission, rate limit. three questions, three places.
act 2 · production
MIDPOINT BREAK
REMEMBER THE WORLD CHAMPIONS?
let's talk about how fast they are.
act 2 · easter egg
WORLD RECORD MATH
16:30500 pieces, the fastest solo on MySpeedPuzzling
4:05one endpoint, Claude Code
= 4endpoints per world record
act 2 · easter egg
SPEAKING OF SPEED.
act 2 · production
"PHP IS SLOW."
— every conference since 2008
act 2 · production
Classic PHP
classic PHP. every. single. request.
act 2 · production
FRANKENPHP
WORKER MODE
boot kernel ─▶ build container ─▶ routing # once
▼
request ─▶ your code ─▶ response ─▶ reset
request ─▶ your code ─▶ response ─▶ reset
request ─▶ …
act 2 · production
PREDICT
GET /api/v1/me
classic 23.6 ms · 167 req/s
worker ?
act 2 · production
REVEAL · p50 LATENCY
classic ████████████████████████ 23.6 ms
worker ███ 3.0 ms
14×
167 → 2,368 requests per second
act 2 · production
PRODUCTION · LAST 30 DAYS · ~10M REQUESTS
23 msp50
115 msp95
→ that's worker mode. in production. right now.
act 2 · production
PHP is alive
PHP in 2026: "dead" since 2008. 23 ms p50.
act 2 · production
BUT.
act 2 · war story
NOVEMBER 2025 · A BIG CINEMA CHAIN HERE
"The website logged fans into other people's accounts."
CineStar, the Traitors finale ticket rush · nafilmu.cz, refresher.cz (paraphrased and translated)
→ I laughed. how can that happen to a company that size?
act 2 · war story
31 DEC 2025 · NEW YEAR'S EVE
02:29 commit "FrankenPHP Worker mode fix"
02:33 deploy ✗ failed02:38 deploy ✗ failed03:09 deploy ✗ failed03:31 Re-run03:35 deploy ✓ live# and I went to sleep
act 2 · war story
Deploy and go to sleep
03:35 · WORKER MODE: ON · GOOD NIGHT
what could possibly go wrong?
act 2 · war story
The inbox on New Year's morning
1 JAN 2026 · 50 unread
act 2 · war story
One sign-on for everyone
perfect single sign-on. one sign-on. for everyone.
act 2 · war story
HOW LONG UNTIL IT WAS REALLY FIXED?
~09:00 worker mode off, by hand on the server1 Jan 15:16 fix #1: reset via reflection on a private property3 Jan 17:07 fix #2: the real one
3 days 14 h
→ and the upstream fix? reported the same afternoon. still open. day 324.
act 2 · war story
THE LESSON
worker mode doesn't make your code stateful.
it reveals it.
→ reset at the START of every request
→ 52 services implement ResetInterface
→ stateless: true, everywhere
→ the rule lives in CLAUDE.md
act 2 · war story
WHO KEPT THE USER IN MEMORY?
a third-party bundle. hold that thought.
act 2 · war story
ACT 3
LIVING WITH IT
measure · alert · fix in an afternoon
act 3 · living with it
OBSERVABILITY
MEASURE EVERYTHING. ALERT ON ALMOST NOTHING.
Sentryerrors, traces, profiles, crons, uptime
own statsAPI usage per token: Redis → Postgres
Grafana stackPrometheus, Loki, Tempo
pagingAlertmanager → Telegram
act 3 · living with it
THE ONE PERFORMANCE ALERT
p90(span.duration) > 500 ms for 30 min
EXCLUDING
GET result_image # slow by design
POST stripe_webhook # Stripe's timing
GET sitemap # bots
GET checkout_success # waits for Stripe
→ every alert must be actionable at 3 a.m.
act 3 · living with it
SEP 2026 · SENTRY WEB-B4
"THE SEARCH FEELS SLOW."
every header search: 135 ms on average. not broken. just… meh.
act 3 · feels slow
THE TRAP I WALKED INTO
src/Query/SearchPuzzle.php
WHERE name ILIKE :searchFullLikeQuery -- trigram index ✓ (since January)
OR identification_number ILIKE :searchFullLikeQuery -- no index
OR ean ILIKE :eanSearchFullLikeQuery -- no index
→ one OR arm without an index = a full table scan. every search.
CREATE INDEX custom_puzzle_identification_number_trgm
ON puzzle USING GIN (identification_number gin_trgm_ops);
CREATE INDEX custom_puzzle_ean_trgm
ON puzzle USING GIN (ean gin_trgm_ops);
src/0 lines changed
"wasgij"75 → 12 ms · production
"cat"79 → 8.5 ms · production
act 3 · feels slow
AND THE TEST DIDN'T MOVE
tests/Controller/Api/V1/PuzzleSearchEndpointTest.php · untouched by the fix
→ the test pins the request and the response. not the implementation.
→ so I can change exactly one thing underneath, and know nothing else moved.
act 3 · feels slow
WHAT TO LOG · AI AGENTS ARE API CLIENTS TOO
$ curl -X POST …/internal-api/series/{seriesId}/publish
[internal_api_audit] Internal API write:
POST /internal-api/series/…/publish answered 200
{ actingPlayerId, targetIds, createdId }
→ ~90 scenario endpoints, an OpenAPI file, and an audit log
act 3 · living with it
REMEMBER THE EXAMPLE ENDPOINT? · WHY IT TOOK 4 MINUTES
same pattern× many endpoints to copy from
read modelthe query already existed
conventionswritten down in CLAUDE.md
teststhat fail loudly, query budgets included
→ a good architecture for humans is a good prompt for agents
act 3 · living with it
CLOSE
THE DECISION I'D UNDO
close
WHO KEPT THE USER IN MEMORY?
THE AUTH0 BUNDLE.
I ran my own fork. and my bug report?
auth0/symfony #227 "causes authentication leak in worker mode"
opened 31 Dec 2025, 14:40 # the same afternoon
comments 0
releases 5.7 · 5.8 · 5.9 · 6.0-beta # none with the fix
status OPEN · day 324
close
The wet-ink signature
2026: getting my own users' password hashes back
close
SPREAD THE WORD.
the few devs I showed this to hated entities as resources. none of them knew a resource can be a plain PHP object.
API Platform is far more powerful than its tutorials.
maybe the most underrated reason to love PHP APIs.