Skip to content
PHP Game Server Compiled to C++: TypePHP AOT Hits 1.16M msg/sec
Game Development 11 min read

PHP Game Server Compiled to C++: TypePHP AOT Hits 1.16M msg/sec

The article examines TSF, a PHP game server framework that uses TypePHP's AOT compiler to translate PHP 8.5 into C++ binaries, achieving 1.16 million messages per second per worker, and details its actor-based architecture, engineering trade-offs, and the author's empirical debugging notes.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub

Counterintuitive Opening

Game server development has an unwritten prejudice chain: C++ looks down on Go, Go on Java, Java and PHP mutually dismiss each other. PHP for game servers? Most assume interpreted execution is too slow for frame loops.

But the GitHub project TSF (TypePHP Server Framework) challenges this: PHP 8.5 source is AOT-compiled to C++ via the TypePHP compiler ( tpc), then built with clang into native binaries, with networking on Swoole. The author reports 1.16 million messages/second per worker (empty echo throughput) and 34,000 concurrent connections on 8 workers (10 Hz heartbeat). These numbers move it beyond toy territory.

What It Actually Does

Beyond the compilation gimmick, TSF implements a conventional game server architecture:

Client (TCP/WS) → Gateway (framing/auth/heartbeat/disconnect retention)
↓ (Actor serial scheduling / lock-free internal)
Service (room / state machine / frame loop)
├── Gameplay packages (room / match / fsm / aoi)
├── Data layer (Repo / memory snapshots / event log)
└── Distributed (UDS cross-process / shard routing)

Gateway layer : TCP/WebSocket ingress, framing, auth, rate limiting, heartbeat, disconnect retention.

Service layer : Actor-style message dispatch. One room = one Service; messages processed serially, so no locks needed inside a service — the design's most valuable guarantee.

Gameplay packages : Room, matcher, state machine, AOI 9-grid vision, frame loop — all optional. Card games don't pay for coordinate packages; MMOs add entities and vision.

Data layer : Declarative ORM (attribute mapping), shard routing, room snapshot crash recovery, append-only event log (for "money must not be lost" scenarios).

Distributed : RPC, service discovery, consistent-hash sharding, circuit breaking, cross-process via UDS.

Toolchain : Excel config export to binary, proto3 codegen, GM admin, tsf watch recompiles and restarts in 1.4–1.9 seconds per line change.

The breadth suggests not a days-old repo (created 2026-11-18, 78 commits) but a long-accumulated brain-dump.

What Is TypePHP?

TypePHP is Swoole's open-source PHP AOT compiler (CLI tool tpc): at compile time it translates PHP source to C++17, then gcc/clang/MSVC produces native binaries, bypassing the Zend VM. The compiler itself is written in pure PHP and fully self-hosting.

It strongly depends on PHP 8.5 ZTS (thread-safe) and the phpx runtime. Compute-intensive workloads see 2×–100× speedups, but only a statically analyzable subset of PHP is supported; dynamic features like eval are restricted. Pure I/O-bound web apps gain little. TSF builds on this foundation.

Official docs: https://www.swoole.com/aot/zh/docs/compile

The README That Made Me Pause

The framework itself isn't novel — Actor model, 9-grid AOI, event sourcing are standard. But TSF's README is an engineering lab notebook with data, not a manual. Three examples:

Textbook conclusions fail under AOT. ECS's Structure-of-Arrays (SoA) contiguous memory is theoretically cache-friendly. In AOT PHP, object arrays took 0.10 ms/frame, while SoA took 0.33 ms — 3.4× slower . Reason: AOT fixes property offsets, allowing -O2 whole-program optimization; parallel arrays incur bounds checks on every index access that the optimizer cannot eliminate. Conclusion: absorb ECS ideas, not its implementation.

Mistakes are recorded, not just successes. A section titled "Correction: mixed isn't slow (I wrote it wrong)" — the author initially attributed a performance difference to mixed type, but alternating load tests revealed it was machine jitter. Another severe error: a hand-written compile config omitted -O2, halving all benchmark numbers, wasting half a sprint "optimizing something already meeting targets".

Bugs come with fingerprints. "8000 connections OOM but RSS only 80 MB" — traced to Swoole reserving 64 KB per connection, counted against PHP's memory_limit, while ZTS accounts memory per-thread. 512 MB ÷ 64 KB = 8192 matches the crash point exactly. The derived methodology: when the crash point is an integer multiple of a config value, suspect the accounting boundary first.

This "phenomenon → hypothesis → elimination → root cause → fix" style is more persuasive than any advocacy piece.

Stay Cool: The Cost of This Path

AOT isn't a free lunch; TSF acknowledges the trade-offs:

No hot code reload. PHP's "edit and run" disappears; hot updates reduced to config reload, embedded scripts, or rolling restarts.

Ecosystem near zero. Most Composer packages break compilation — global executable statements, readonly property reflection writes, etc. Doctrine-level ORM hits a wall, so the data layer had to be custom-built.

Strict coding constraints. mixed banned, closure captures don't auto-write-back, callback signatures must match exactly, variable types fixed at first assignment — each rule hides a "silent bug that doesn't error but doesn't work".

Toolchain still young. tpc 0.9.6 still fixing semantic issues; several README sections note "old version triggered, new version cannot reproduce".

In short, choosing this path trades PHP's ecosystem and flexibility for C++-level runtime performance while keeping PHP syntax and dev feel. The bet: some developers want performance but genuinely don't want to write C++.

Summary

TSF is currently a feasibility proof + pitfall map , not a production-ready choice — multi-worker room ownership, cross-node state sync are honestly marked "not done yet".

But it delivers two values beyond the project:

It proves PHP AOT for stateful real-time services is engineering-viable , with every stumbling block documented. Future adopters, whether using TSF or not, gain a valuable pitfall checklist.

It showcases a rare engineering culture: every design decision backed by measured data, every wrong conclusion publicly corrected, every "not doing X" justified. Answers to "why not Open Match", "why not incremental snapshots", "why recovery rate-limiting tested unnecessary" reveal judgment more than feature lists.

Game servers have lacked a new narrative for years. C++ is heavy, GC in Go interferes with frame loops, Skynet guards its Lua niche. TSF may not be the answer, but it poses a new question: If PHP is no longer slow, what would you write your game server in?

Project URL: https://github.com/hhr0815hhr/tsf

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPAOT CompilationEngineering PracticesGame ServerPerformance BenchmarkingActor ModelSwooleTypePHP
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.