Skip to content

PCRE Router: One Regex for 10 000 Routes

4 min read Notes

PCRE Router: One Regex for 10 000 Routes

Every PHP router has a loop in it. Match, fail, advance, match again, until a pattern sticks. At forty routes nobody notices. At four hundred the loop runs on every request, and the cost of dispatch quietly becomes a line in the profile.

Code: ATOM, GPL-3.0 licensed.

ATOM takes the other route: the whole table is compiled into a single PCRE pattern, and dispatch is one preg_match call. That design choice decides how the rest of the framework looks, so it is worth reading on its own.

How a pcre router compiles a table

A route table is a list of paths with placeholders. /users/{id} becomes a pattern with a capture group where the placeholder sits, and every literal character around it is escaped, so a dot in /v1.2/users matches a dot and not any character.

The trick that makes a single match possible is PCRE branch reset. Inside (?|...), alternatives share the same capture group numbers, so /users/([^/]+) in branch one and /posts/([^/]+) in branch two both write group 2. Without it, a table of ten thousand routes needs ten thousand group numbers.

Each alternative also carries a (*MARK:name). When the pattern matches, the mark records which alternative won. The framework reads the mark, looks up the route by name, and hands the request to its handler. One match produces both the route and its parameters.

$app->router->get('/users/{id}', 'UserController@show', 'user.show');
$app->router->group('/api', ['Auth'], function ($r) {
    $r->post('/users', 'UserController@create');
});

Groups, names and URL generation

Named routes are not decoration here: url('user.show', ['id' => 7]) needs the reverse of the compiled pattern, and the name is the key that makes the reverse lookup possible.

Groups attach middleware to a path prefix, so /api can require authentication without repeating the attribute on twelve routes. The middleware stack is an onion, and each item is a closure, an object or a class name.

The cache follows the table, not a timer

Compiling ten thousand alternatives is expensive, so the result is written to a file and reused. The cache key comes from the route signatures, which means adding a route invalidates the cache on the next request without a manual purge.

bin/atom cache clears it when you want a clean build, and bin/atom routes prints the table with the compiled sizes. Environment switch: APP_ROUTE_CACHE, next to the view cache and the cache driver.

Where one regex stops being the right tool

Three limits are worth knowing before copying the approach.

The first is cold start. A pattern with ten thousand alternatives takes time to compile, and that cost lands on the first request after a deploy. The file cache turns it into a one-off, and until the file exists the request waits.

The second is debugging. A route that does not match gives you one failing preg_match, not the index of the branch that should have matched. Dumping the compiled pattern helps, and it is not the same as reading a clean route list. PHP’s backtracking limits also apply.

The third is host-based routing. If the same path behaves differently on api.example.com and www.example.com, the host has to become part of the pattern, and the table grows by a second dimension. It works; it just costs clarity.

For route counts in the hundreds, a loop is fine and easier to read. The single-pattern design pays at API scale, where the table never shrinks.

What else rides on the same entry point

Request uses property hooks, parses a JSON body, extracts a Bearer token and honours _method spoofing, which covers most of a REST API without extra packages. Response offers html, json, text, redirect and noContent, plus cookie and cache headers.

Validation runs on 18 attribute rules against a DTO, and #[RateLimit(max: 60, window: 60)] limits requests per IP. The CLI exposes list, help, routes, cache and ws:serve, so the route table and the cache are inspectable from a terminal.

Testing dispatch without a server

The package ships an HttpClient with assertions:

$client->get('/users/7')->assertOk()->assertJson(['id' => 7]);

728 tests, 1108 assertions, 85.29% line coverage, PHPStan at level 5. The HTTP layer is tested through the same rewrite rules production uses, because a router tested behind a different front controller is a router that 404s in production with a green suite.

Two related notes in this catalogue cover the surrounding decisions: choosing a response format so clients parse one shape, and why small APIs beat one big integration when the surface grows faster than the team.

Background: the PCRE pattern syntax and ATOM on Packagist.

Custom work

Need an API that does not exist yet?

Describe the task and the response format. We will estimate the endpoint, the integration and the maintenance.

Start a conversation