Refactoring a Seamless Large-World Single-Server Architecture: Practices and Pitfalls

    Building a seamless large-world game requires more than just continuous map loading; it demands continuous crowd and state management. This article explores the architectural refactoring needed to maintain a single authoritative copy of the world state. It covers key technical pillars, including spatial subdivision for addressable discrete units, floating-origin coordinate systems for 3D precision, gravity fields as spatial properties, Area of Interest (AOI) state synchronization, dynamic load redistribution through online migration, and robust persistence and observability strategies.

    1. The Starting Point: Why a “Large Map” Is Not a “Large World”

    Many teams treating seamless large maps assume that “continuous map loading” is the ultimate goal. However, this only solves spatial continuity, not crowd continuity. When the same world state is naturally split across multiple processes and logical partitions, players might physically exist under the same starry sky but are logically isolated in different instances. This structurally limits social interactions, trading, and large-scale battles.

    The real watershed is whether the world state has only a single authoritative copy. Achieving this requires refactoring three things simultaneously: spatial indexing methods, state synchronization models, and dynamic load redistribution capabilities. These three are interdependent. If any link retains old assumptions, the system eventually degenerates into a “pseudo-single-server.”

    2. Spatial Subdivision: Turning a Continuous World into Addressable Discrete Units

    An infinite world cannot be loaded into memory all at once; it must be subdivided. In engineering, a three-tier structure is commonly used:

    1. Coarse-grained partitioning: Using fixed-edge cubes (cells) as the minimal unit for scheduling and persistence;
    2. Medium-grained indexing: Building quadtrees/octrees above the grids to quickly answer “which entities are near a coordinate”;
    3. Fine-grained proximity: Using spatial hashing within grids for entity bucketing to serve combat checks and visibility calculations.
    1. CELL_SIZE = 256.0
    2. def cell_key(x, y, z):
    3. return (int(x // CELL_SIZE), int(y // CELL_SIZE), int(z // CELL_SIZE))
    4. class SpatialGrid:
    5. def __init__(self):
    6. self.buckets = {}
    7. def insert(self, entity):
    8. self.buckets.setdefault(cell_key(*entity.pos), set()).add(entity.id)
    9. def query(self, pos, radius):
    10. cx, cy, cz = cell_key(*pos)
    11. span = int(radius // CELL_SIZE) + 1
    12. result = set()
    13. for dx in range(-span, span + 1):
    14. for dy in range(-span, span + 1):
    15. for dz in range(-span, span + 1):
    16. result |= self.buckets.get((cx+dx, cy+dy, cz+dz), set())
    17. return result

    The key constraint is that partition boundaries must be statelessly derivable: given a coordinate, you can calculate the belonging partition without a lookup table. This allows any process to take over any region at any time.

    3. Coordinate System and Precision: The Most Underestimated Pitfall in 3D Large Worlds

    When building ultra-large-scale worlds in 3D space, floating-point precision is a hard constraint. As the absolute value of coordinates increases, the minimum resolvable interval of single-precision floats expands, causing distant objects to jitter, collision penetration, and animation misalignment. The industry-standard solution is mixed precision + floating origin:

    • The authoritative server uses fixed-point numbers or double precision to store absolute coordinates;
    • Each client/partition maintains a local origin, using relative coordinates for rendering;
    • When an entity crosses a threshold distance, the local origin is translated, and all relative quantities are synchronized and corrected.
    1. Absolute coordinates (fixed-point 64-bit) --> Partition local coordinates (relative origin, float32) --> Rendering
    2. ^ |
    3. |____ Floating origin (triggered by crossing threshold) ________|

    4. Multiple Gravity Fields: Making “Physics Rules” Spatial Attributes

    Sci-fi themes often require different gravity environments within the same world. The correct approach is not to write special-case logic for each planet, but to abstract gravity as a field superimposed on space:

    • Each celestial body registers a gravity source (mass, radius, influence radius, attenuation model);
    • The combined acceleration at a sampling point is the vector sum of all gravity sources within the influence radius;
    • Field data loads/unloads with the partition, and entities switch fields synchronously upon migration;
    • Field parameters are configuration-driven, allowing designers to tweak without changing code.
    1. a_total(p) = Σ G * m_i * (p_i - p) / (|p_i - p|^2 + ε)^(3/2)

    Where ε is used to avoid singularities. This abstraction simultaneously supports orbital motion, low-gravity jumping, and the smooth transition of “switching to surface gravity upon entering the atmosphere.”

    5. State Synchronization: Interest Management Determines Bandwidth Limits

    In a single-shard architecture, the synchronization volume grows quadratically with crowd density, necessitating strict Area of Interest (AOI) management:

    • Enter/leave eventification: Only push deltas; do not poll full snapshots;
    • Layered precision: Reduce frequency and precision for distant entities; high precision and frequency for near ones;
    • Priority queue: Combat-related updates take priority; decorative performances can be dropped;
    • Aggregate compression: Batch encode entities of the same type in the same area to reduce header overhead.
    1. if distance < NEAR: freq = 20Hz, precision = full
    2. elif distance < MID: freq = 5Hz, precision = quantized
    3. elif visible: freq = 1Hz, precision = coarse
    4. else: no update, only enter/leave events

    6. Dynamic Load Redistribution: Ensuring “One World” Isn’t Boxed into a Single Machine

    A single authoritative copy does not mean a single-machine process. The viable path is to slice the world into numerous partitions, assigned by a scheduler to worker processes, supporting online migration:

    1. The scheduler monitors entity count, CPU, and bandwidth of each partition;
    2. When migration triggers, first “freeze” writes to that partition and take a state snapshot;
    3. The target process loads the snapshot, establishes subscriptions, and verifies with dual-writes;
    4. Switch the authoritative pointer, unfreeze, and clients only perceive a brief delay.

    Migration must be designed at partition granularity and with idempotency as a prerequisite. Any “migration failure rollback” path must be genuinely rehearsed in stress tests.

    7. Persistence and Consistency Boundaries

    • Choose spatial partition ID as the shard key to ensure writes to the same region land on the same shard, avoiding cross-shard transactions;
    • Store world data and player data separately; the former can be rebuilt, while the latter requires strong durability;
    • Adopt a “memory authority + async flush + operation log replay” structure to balance responsiveness and recovery;
    • Use message queues for eventual consistency in cross-partition interactions (like cross region trades), clarifying compensation semantics.

    8. Observability and Capacity Verification

    The biggest risk in large-world projects is “discovering it can’t handle the load only after launch.” It is recommended to build ahead of time:

    • Metrics: Partition entity density, sync bandwidth per person, migration duration, snapshot size, GC/memory watermark;
    • Logs and tracing: Full-link traces for a single cross-partition interaction to pinpoint latency sources;
    • Stress testing: Bots distributed according to real behavior models rather than uniform scattering, as hotspot areas are the real bottlenecks;
    • Alarms: Set thresholds for partition overload, migration failure rates, and flush backlogs.

    When deployed in the cloud, these capabilities usually map to general categories: container platforms host elastic worker processes, object storage saves world snapshots, message queues handle cross-partition events, and logging services with monitoring alarms manage observability. Baidu AI Cloud offers corresponding capabilities in these general categories, which can be combined as needed without binding to proprietary interface designs.

    9. Common Pitfalls Checklist

    • Implementing “seamless” as client-side stitching while the authoritative layer remains sharded;
    • Partition granularity being too large, leading to high migration costs and unbreakable hotspots;
    • Ignoring precision issues, resulting in extremely high rework costs later;
    • AOI only doing distance filtering without frequency/precision reduction;
    • Lacking online migration capabilities, relying solely on offline scaling;
    • Using uniform loads for stress testing, masking real hotspots.

    10. Conclusion

    Moving from a “sharded large map” to a “single-shard infinite world” is essentially a replacement of architectural assumptions: space is addressable, state is migratable, rules are configurable, and load is redistributable. Once these four hold true, the world’s limit is no longer determined by a single machine, but by scheduling and synchronization efficiency. For developers, the earlier precision, partition granularity, and migration paths are finalized, the less rework will be needed later.