DEV Community

seoulsmith
seoulsmith

Posted on Originally published at seoulsmith.com

One haystack shared by every Roblox server

Originally published on seoulsmith.com.

One Haystack is a Roblox game with a single premise: every server digs the same pile of hay, and there is exactly one needle in it. When someone finds it, the season ends everywhere and a new pile starts.

That premise turns a simple digging game into a small distributed-systems problem. Roblox servers do not share memory. A server holds up to 20 players, lives for as long as people are in it, and can vanish without warning. This post is about how those servers agree on how much of the pile is left, without melting a shared key and without counting the same hay twice.

I'll leave out one part on purpose: how the needle's location is stored and decided. That is the one thing in the design that players would benefit from knowing.

Problem

Roblox gives you two cross-server stores. DataStore is durable and slow-ish. MemoryStore is fast, expires, and has a request budget. The limits I designed against (Creator Docs, checked 2026-11-10):

  • Request units: 1000 + 120 × concurrent players per minute, for the whole game
  • Per HashMap key: roughly 5,000 write and 15,000 read units per minute, and UpdateAsync costs at least 2 units and counts against both
  • Queues and sorted maps: 1,000,000 items per structure

The naive design is one key, strawsLeft, decremented on every swing. A swing happens once per second per player. That is a single hot key written by every player in the game, which is exactly the shape the per-key limit exists to stop.

There is a second problem that only showed up once I ran the economy simulation. A new player with bare hands and a maxed player on the last tool differ by about 60× in straws per minute. Any fixed pile size is wrong for someone: with a fixed 5 million straws, my budget script put a 20-player game of new players at 1.7–3.8 hours to the needle, and a game of veterans at 3–8 minutes. I wanted a season to last days.

What I tried

A queue of chunks. Split the pile into chunks, put them in a MemoryStore queue, let each server pop one. Queues have an invisibility timeout, so a crashed server's chunk would reappear on its own. I dropped it for two reasons. At 10,000 concurrent players the chunk count goes past 1.3 million, over the 1,000,000 item limit. And I could not find a documented maximum for the invisibility timeout, so I did not want the design to depend on it.

Chunks sized in straws. My first chunk definition was "N straws". Because of the 60× speed gap, that makes the number of store requests proportional to how fast the players in a server happen to dig. A server of veterans would allocate and complete chunks 60 times as often as a server of beginners.

Decision

Three pieces.

1. A chunk is time, not hay. A chunk is "what one server digs in 7 minutes". The straw count per chunk is computed per season from measured speed. The request rate then depends only on the number of servers. In the budget table the total stays at about 1.4% of quota from 5 players to 50,000 (for 50,000 players: 85,725 units per minute against a quota of 6,001,000), and most of that is polling, not writes.

2. K counters instead of one. Allocation and completion each use K = 8 HashMap keys (alloc:0..7, done:0..7). Chunk ids interleave across shards, so chunk id = k + K·i is the i-th chunk of shard k. A server asking for work increments one shard's counter with UpdateAsync and gets a chunk id nobody else has. At 50,000 players that is about 149 write units per minute per shard key, against a limit of roughly 5,000.

3. Aggregate per chunk, idempotently. Servers never report straws. They report "chunk finished", once. Each server keeps the set of chunk ids it has already reported, and marks a chunk as reported before the write, so a write whose outcome is unknown is not retried into a double count. The global progress bar is the sum of the K done counters, polled every 30 seconds.

The trade-off is precision. Progress moves in chunk-sized steps, and a chunk held by a server that shuts down is simply lost: the bar may never reach 100%. I accepted that, because the season does not end at 100%. It ends when the needle is found.

DataStore holds the season definition (the source of truth). MemoryStore holds progress (a cache). A checkpoint every 10 minutes copies counters back, so if MemoryStore is wiped, at most 10 minutes of progress is lost.

Code

Shard choice. The first version picked the least-advanced shard, and in the spike all three virtual servers read the same counters and took chunks 0, 4 and 8, which are all shard 0. Ties are now broken randomly:

export function shardOrder(alloc: readonly number[], perShard: number, shards: number, randomInt: RandomInt): number[] {
    const open: number[] = [];
    for (let k = 0; k < shards; k++) if ((alloc[k] ?? 0) < perShard) open.push(k);
    const order: number[] = [];
    while (open.size() > 0) {
        let least = math.huge;
        for (const k of open) least = math.min(least, alloc[k] ?? 0);
        const ties = open.filter((k) => (alloc[k] ?? 0) === least);
        const chosen = ties[randomInt(0, ties.size() - 1)];
        order.push(chosen);
        open.remove(open.indexOf(chosen));
    }
    return order;
}
Enter fullscreen mode Exit fullscreen mode

Completion, counted once per chunk:

complete(seasonId: string, chunk: number, minutes: number): boolean {
    const rec = this.record;
    if (!rec || rec.id !== seasonId) return false;
    const key = `${seasonId}:${chunk}`;
    if (this.completed.has(key)) return false;
    this.completed.add(key); // the write may have landed even if it reports failure
    const k = shardOf(chunk, this.shards);
    const res = this.liveUpdate<DoneCount>(doneKey(k), (old) => {
        const base = old ?? this.baseDone(k);
        return { n: base.n + 1, minutes: base.minutes + math.max(0, minutes) };
    });
    if (res.ok && res.value) this.done[k] = res.value;
    return res.ok;
}
Enter fullscreen mode Exit fullscreen mode

Note minutes: each completion also adds the server-minutes spent. That feeds the next piece.

Season size. No assumed average speed, only what was actually dug (one tunable value is left out):

export function seasonSize(dailyStraws: number | undefined, s: SeasonSizing = SEASON): number {
    if (dailyStraws === undefined || dailyStraws <= 0) return s.minStraws;
    const midDays = (s.targetDaysMin + s.targetDaysMax) / 2;
    const midBand = /* expected progress when a season ends (tunable, left out) */;
    return math.max(s.minStraws, math.floor((dailyStraws * midDays) / midBand));
}
Enter fullscreen mode Exit fullscreen mode

dailyStraws is the average of the last 7 days of real digging. midDays is the middle of the target season length (3 to 7 days). midBand is the expected progress at which a season ends. The floor is 5 million straws, which is also what the first season uses because there is no history yet. Chunk size comes from the same record: straws dug divided by server-minutes, times 7.

Because the size follows history, it lags. If the player count jumps mid-season, the pile would be gone in hours. At each checkpoint the server projects the current allocation rate forward, and if the season is on track to end in under 3 days, it adds chunks. It only ever grows the pile, never shrinks it.

Result

What I have actually measured:

  • A spike with three virtual servers against the real MemoryStore and DataStore APIs: 32 and 33 allocations in two runs with no duplicate chunk id, no quota warnings.
  • The same spike showed servers only noticed the end of a season at a chunk boundary, which with 7-minute chunks means up to 7 minutes late. After moving that check to the polling loop, a 420-second chunk was abandoned 8–9 seconds after the season ended (with a 5-second poll in the spike).
  • Two real game servers on the same season: they received different chunks, and one server's progress display followed the other's completed chunks at each poll (90 → 117 → 196 → 276).
  • The whole module takes its clock and its stores as injected dependencies, so the allocation, completion and recovery paths run under TestEZ against a fake MemoryStore. The suite was at 279 passing at the last change to this module.

What I have not measured: anything above a handful of servers. The load numbers are from a budget script, not production. The first public season will be the first real test of the sizing formula, and it starts from the 5 million floor with no history, so I expect the grow-the-pile path to run.

One Haystack is on Roblox: https://www.roblox.com/join/fjivi

Top comments (0)