Table of Contents
- The Problem with Broadcasting Everything
- Why a Quadtree
- The Spatial Index in Our Game Server
- What Gets Indexed
- From Movement Intent to Nearby Players
- Streaming Enemies Without Pop-In
- Redis, Workers, and Shared State
- Edge Cases and Lessons Learned
- What Comes Next
The Problem with Broadcasting Everything
MageQuest is an MMORPG with a procedurally generated, effectively infinite world. The browser client streams a 3x3 window of 64x64-tile areas around the player. Each area is 2048x2048 world pixels, and players can walk across area boundaries without a loading screen.
That creates a deceptively simple question: who needs to know about a player’s action?
The naive answer is “everyone.” When a player moves, attacks, or changes appearance, send that update to every connected socket. It works in a demo with two players. It does not work in a world with hundreds of players, because the amount of work grows with the square of the player count: every player produces updates for every other player.
The gold player’s update reaches every other player (gold lines), while the faint lines show every possible pair. Broadcast fan-out grows with the square of the player count, and most of those deliveries are irrelevant.
Most of those updates are irrelevant. A player three maps away does not need to see another player’s walk cycle. A monster spawning on the other side of the world should not wake up a socket that cannot see it. The server needs to answer a much narrower question:
Given a point in the world, which entities are close enough to matter?
That is a spatial query, and the simplest data structure for it in a tiled 2D world is a quadtree.
Why a Quadtree
A quadtree recursively divides a two-dimensional space into four quadrants. Each node holds a small bucket of points. When a bucket fills up, the node splits into four children and redistributes its points. A range query discards entire branches that cannot intersect the search circle, then checks only the remaining points.
For a world where most actions are local, this turns a global scan into a handful of node visits. The complexity is roughly O(log n + k) for k results, rather than O(n) per query.
Our game server’s implementation deliberately keeps the core small:
class QuadNode<T extends SpatialPoint> {
items: T[] = []
children: QuadNode<T>[] | null = null
constructor(
readonly bounds: SpatialBounds,
readonly depth: number,
) {}
}The tree defaults to a capacity of eight points per node and a maximum depth of twelve. The root covers the same coordinate range the rest of the server accepts, from -1,000,000 to 1,000,000 on both axes.
Insertion walks to the correct child until it reaches a leaf. If the leaf exceeds its capacity, it splits:
#split(node: QuadNode<T>) {
const halfWidth = node.bounds.width / 2
const halfHeight = node.bounds.height / 2
const { x, y } = node.bounds
node.children = [
new QuadNode({ x, y, width: halfWidth, height: halfHeight }, node.depth + 1),
new QuadNode({ x: x + halfWidth, y, width: halfWidth, height: halfHeight }, node.depth + 1),
new QuadNode({ x, y: y + halfHeight, width: halfWidth, height: halfHeight }, node.depth + 1),
new QuadNode({ x: x + halfWidth, y: y + halfHeight, width: halfWidth, height: halfHeight }, node.depth + 1),
]
// redistribute the leaf's items into the children
}A circular query prunes any node whose bounds do not touch the search circle, then applies the exact squared-distance test to the points inside:
query(x: number, y: number, radius: number): T[] {
const found: T[] = []
this.#query(this.root, x, y, radius, found)
return found
}The key detail is the exact distance check. A quadtree query is a broad phase. It returns candidates whose nodes overlap the circle, but a point in the corner of an intersecting node may still be outside the radius. Filtering after the tree walk keeps the result precise without making the tree itself more complicated.
The cyan circle is the query. Gold areas are the branches the tree visits; green dots are returned; gray dots sit in branches that are skipped entirely.
Gold nodes are candidates because they intersect the circle. Green dots pass the exact distance check; orange dots with a cross are inside a candidate node but outside the radius; gray dots were never visited.
The quadtree is a broad-phase index, not the final answer.
The Spatial Index in Our Game Server
The server does not use the raw tree directly in gameplay code. It wraps the tree in a SpatialIndex that tracks entities by id:
export interface SpatialEntity extends SpatialPoint {
id: string
kind: 'player' | 'enemy' | 'npc' | 'item'
area: string
data?: unknown
}The wrapper maintains both a Map<string, T> and the quadtree. Calling set removes the old position before inserting the new one, which matters because players and enemies move. Querying supports filters for area, kind, and an excluded id:
query({ x, y, radius, area, kind, excludeId }: SpatialQuery): T[] {
return this.tree.query(x, y, radius).filter(entity => {
if (excludeId && entity.id === excludeId) return false
if (area && entity.area !== area) return false
if (kind && entity.kind !== kind) return false
return true
})
}That small API is enough for several different proximity problems:
- Players: local movement state, used for player/entity queries.
- Enemies: streamed spawns that should be visible to nearby players.
- NPCs: static area residents that should be findable by proximity.
- Items: the same interface supports future shared drops and pickup ranges.
The area field is not part of the tree geometry; it is a gameplay filter. The tree works in global world coordinates, while the server also groups things by 2048-pixel area ids such as 100001_100000. Both views are useful: the tree answers “what is near this point?” and the area id answers “which chunk of content is this client currently streaming?”
What Gets Indexed
The server indexes entities whenever its local state changes.
Players are indexed when their presence is announced and every time a movement intent arrives:
function indexPlayerState(state: PresenceState) {
const position = positionAt(state, Date.now())
worldIndex.set({
id: `player:${state.userId}`,
kind: 'player',
area: state.area,
x: position.x,
y: position.y,
data: state,
})
}The server does not wait for a packet per frame. Movement is intent-based: the client sends position, direction, and action on change, then a 1-second moving / 5-second idle heartbeat. positionAt extrapolates the same way every consumer does, using the client’s cardinal and diagonal speeds. That means the index can answer a query at any moment, not only at the instant an intent arrived.
Enemies are loaded from Redis per area and mirrored into the index:
function indexAreaEnemies(area: string, enemies: SpawnEnemy[]) {
const current = new Set<string>()
for (const enemy of enemies) {
if (enemy.dead) continue
current.add(enemy.id)
worldIndex.set(enemyIndexEntity(enemy))
}
// delete entries that no longer exist in this area
}Only living enemies are indexed. A defeated enemy is removed immediately, which is also how nearby clients receive the removal event. NPCs are indexed from the area service when an area is refreshed. Their positions are static, but indexing them now keeps the door open for proximity interactions without adding a second lookup path later.
From Movement Intent to Nearby Players
There are two proximity paths in our game server, and it is worth being explicit about the split.
Player-to-player presence is driven by Redis. The server writes each player’s latest state into a Redis hash and publishes a state event on magequest:realtime. Every worker subscribes to that channel. When a worker receives an update, it looks at the sockets connected to that worker and decides which ones are close enough:
const remote = event.state
const remotePosition = positionAt(remote, now)
for (const [socketId, { ws, userId }] of localSockets) {
if (userId === remote.userId) continue
const local = localStates.get(userId)
if (!local) continue
const localPosition = positionAt(local, now)
const sameArea = local.area === remote.area
const inRange = sameArea && distanceBetween(localPosition, remotePosition)
if (!inRange) continue
send(ws, 90, { players: [remote], removed: [], full: false })
}Presence uses a 2500-pixel radius. The area check comes first because two players on opposite sides of an area boundary can be geometrically close but still belong to different streamed maps. Answers are sent as deltas: { players: [one], removed: [], full: false } for an update, and a removal when someone leaves the radius or disconnects. A full: true snapshot is sent on connect, character select, and area changes.
The Redis hash is the cross-worker source of truth. The quadtree indexes the local player states and is available for local spatial queries, but player presence fan-out intentionally stays on the pub/sub path: it already has the authoritative state and needs to reach workers that may not have indexed a remote player yet.
Enemy and shared-world proximity uses the quadtree directly. When the server needs the monsters around a player, it queries the index instead of scanning the Redis spawn hash or every enemy in the world:
function nearbyEnemies(_area: string, origin: { x: number; y: number }): SpawnEnemy[] {
return worldIndex
.query({ x: origin.x, y: origin.y, radius: SPAWN_VIEW_RADIUS, kind: 'enemy' })
.map(entity => entity.data as SpawnEnemy)
.filter(enemy => enemy && !enemy.dead)
}Enemy streaming uses a 2000-pixel radius. Areas are only a spawn grouping; a player standing at an area edge still sees monsters across the border, so the query stays in world space.
Streaming Enemies Without Pop-In
The spawner is a separate system built on the same spatial index.
Spawn rules are derived from the area id’s distance to the starting village. 100000_100000 is the safe starting area and spawns nothing. The first ring gets a modest population of slimes; farther rings add goblins, wolves, and skeletons, with larger counts and longer respawn delays. Authored areas can override any of those values in AREA_SPAWN_OVERRIDES.
The server stores each area’s monsters in a Redis hash, magequest:spawns:<areaId>. A five-second sweep tops up occupied areas, but it only counts alive enemies toward the target. Defeated enemies reserve their slot until their respawn timer expires, so the world does not instantly over-spawn.
The interesting part is placement. New enemies must not appear on a player’s screen. The spawner picks points in a ring around a player and rejects any point within 900 pixels of any player:
const point = {
x: origin.x + localX,
y: origin.y + localY,
}
const safe = players.every(player =>
Math.hypot(player.x - point.x, player.y - point.y) >= SPAWN_SAFE_RADIUS
)Points also have to be walkable according to the generated area’s collision grid. If an area is already full from an earlier session but all of its monsters are far away, the spawner adds a small local minimum (up to five) within the player’s 2000-pixel view radius. That is what makes re-entering a persisted area feel populated instead of empty.
When a spawn happens, the server publishes an enemies event on the same Redis channel. Nearby workers receive it and send an event 73 delta to the sockets in range. In the common case, the new monster is outside the screen but inside the streaming radius, so the client has it ready before the player walks into view.
Redis, Workers, and Shared State
Our game server can run more than one worker process. A quadtree in one process cannot see a player connected to another process, so the architecture separates two concerns:
- Shared truth lives in Redis. Presence, spawns, respawn points, and generated area caches are all shared. A server restart reloads the same spawns, and clearing Redis starts the world over.
- Local proximity lives in the worker’s index. Each worker indexes only what it has loaded and what its own players need. It does not try to keep a global quadtree of every player in the world.
Redis pub/sub closes the gap. A movement update is published once and delivered to every worker. Each worker then answers a local question: “which of my sockets should receive this?” Cross-worker delivery is not a global broadcast; it is a set of targeted local sends.
The same pattern handles enemy removals. When a player defeats a monster, the server validates that the enemy exists and is within 800 pixels of the player’s presence position, marks it dead in Redis, removes it from the index, and publishes a removal event. Every worker that knows about that enemy drops it from the corresponding clients. The monster’s respawn timer then creates a fresh enemy away from players.
Edge Cases and Lessons Learned
A few details mattered more than the tree itself.
Exact filtering after the tree query. A node can intersect the query circle while its points do not. Always apply the squared-distance check to the returned candidates.
Coordinates are shared, but meanings are not. The client, the area service, the spawner, and the quadtree all use world pixels, but the area id is a separate 2048-pixel grid. Mixing local tile coordinates with global world coordinates is the easiest way to make monsters spawn in the wrong place.
Moving entities need remove-and-reinsert. Updating a point in place would leave the tree’s node membership stale. SpatialIndex.set deletes the old entry first.
Dead entities should leave the index. Keeping corpses in the tree means queries keep returning things clients cannot see or interact with. The spawner indexes only living enemies and removes defeated ones immediately.
Area boundaries are not query boundaries. Players near an edge need entities from the next area. The presence system uses an area check for its own consistency, while the enemy stream queries world space and relies on distance. Different systems can legitimately make different choices here.
Safe spawning is a gameplay rule, not a rendering rule. The 900-pixel exclusion zone is enforced on the server. The client never decides where a monster appears, so two players cannot disagree about a spawn.
What Comes Next
The quadtree is already the foundation for more than monsters.
The SpatialEntity type includes item, which is the hook for shared dropped loot. A drop can be written to Redis, indexed by area and position, and streamed to nearby players with the same delta pattern used for enemies. Pickup validation can use the same spatial query instead of trusting a client’s claimed position.
The next step for enemies is to make their movement server-aware. Today the server owns spawn location, shared lifetime, and kill removal; the client still runs the moment-to-moment aggro simulation. Moving that simulation into the game server would let the quadtree broadcast enemy positions and attacks exactly like player presence, with the same area and radius rules.
The pattern scales because it is boring in the right way: a small spatial index answers “what is nearby?”, Redis carries shared truth between workers, and the WebSocket layer only sends what a player can plausibly see. That is enough to make a large, persistent world feel local.
You can play the result at magequest.online.






