Dev.to Security πŸ” Cybersecurity πŸ‘ 2 πŸ“– 4 min read

Hardening Roblox RemoteEvents in Strict Luau: Server-Authoritative Rate Limits, Cooldowns & Upgrade DAGs

Any Roblox tycoon, simulator, or action game that treats RemoteEvent.OnServerEvent parameters as trustworthy will see its economy broken within hours of launch. Attackers do not need to decompile server scripts to exploi

Any Roblox tycoon, simulator, or action game that treats RemoteEvent.OnServerEvent parameters as trustworthy will see its economy broken within hours of launch. Attackers do not need to decompile server scripts to exploit weak boundariesβ€”they only need to fire existing remotes with crafted arguments:

  • Packet replay & burst flooding: Re-invoking AttackRemote or ClaimReward 50 times in a single frame before client-side UI cooldowns reset.
  • Negative-quantity exploits: Passing quantity = -1000 to a shop remote so price * quantity becomes negative and credits currency instead of deducting it.
  • NaN and Inf injection: Sending 0/0 (NaN) or math.huge. In Luau, NaN < 0 and NaN >= cost both evaluate to false, silently bypassing naive guard clauses and corrupting saved DataStore numbers.
  • Circular upgrade graph deadlocks: Shipping a tech-tree or tycoon dropper graph where Node A requires Node B and Node B requires Node A (or a missing prerequisite ID), soft-locking progression mid-session.

Below are three production patterns in --!strict Luau that close these failure modes at the server boundary.

1. Strict Input Sanitization & Token-Bucket Rate Limiting

Never trust client-supplied prices, cooldown durations, or damage numbers. Accept only an opaque actionId or integer quantity, validate runtime types (Luau type annotations are erased at runtime), reject non-finite numbers via math.isfinite (or val == val and math.abs(val) < math.huge), and enforce a per-player sliding-window / token-bucket limiter using monotonic os.clock().

--!strict
local RateLimiter = {}

type Bucket = { tokens: number, lastRefill: number }
local buckets: { [Player]: { [string]: Bucket } } = {}

function RateLimiter.allow(player: Player, key: string, maxTokens: number, refillPerSec: number): boolean
    local now = os.clock()
    local playerBuckets = buckets[player]
    if not playerBuckets then
        playerBuckets = {}
        buckets[player] = playerBuckets
    end
    local b = playerBuckets[key]
    if not b then
        b = { tokens = maxTokens - 1, lastRefill = now }
        playerBuckets[key] = b
        return true
    end
    b.tokens = math.min(maxTokens, b.tokens + (now - b.lastRefill) * refillPerSec)
    b.lastRefill = now
    if b.tokens < 1 then return false end
    b.tokens -= 1
    return true
end

function RateLimiter.sanitizePositiveInt(raw: unknown, maxAllowed: number): number?
    if typeof(raw) ~= "number" or not math.isfinite(raw) then
        return nil
    end
    local n = math.floor(raw)
    if n ~= raw or n < 1 or n > maxAllowed then return nil end
    return n
end

return RateLimiter

Call Players.PlayerRemoving:Connect(function(p) buckets[p] = nil end) so disconnected player entries never leak memory.

2. Validating Upgrade Tech Trees at Server Boot with Kahn's Topological Sort

In tycoons and RPG skill trees, upgrade prerequisites form a Directed Acyclic Graph (DAG). Instead of discovering a cycle or typo in production when players hit an unlockable wall, run Kahn's algorithm once at server startup against your catalog table:

--!strict
export type UpgradeNode = { id: string, cost: number, deps: { string } }

local function validateUpgradeDAG(catalog: { [string]: UpgradeNode }): (boolean, string?)
    local inDegree: { [string]: number } = {}
    local adj: { [string]: { string } } = {}

    for id, node in catalog do
        inDegree[id] = inDegree[id] or 0
        adj[id] = adj[id] or {}
        for _, depId in node.deps do
            if not catalog[depId] then
                return false, `Missing prerequisite "{depId}" referenced by "{id}"`
            end
            adj[depId] = adj[depId] or {}
            table.insert(adj[depId], id)
            inDegree[id] += 1
        end
    end

    local queue: { string } = {}
    local totalNodes = 0
    for id, deg in inDegree do
        totalNodes += 1
        if deg == 0 then table.insert(queue, id) end
    end

    local visited = 0
    while #queue > 0 do
        local curr = table.remove(queue, 1) :: string
        visited += 1
        for _, nxt in adj[curr] do
            inDegree[nxt] -= 1
            if inDegree[nxt] == 0 then table.insert(queue, nxt) end
        end
    end

    if visited ~= totalNodes then
        return false, "Cycle detected in upgrade DAG"
    end
    return true, nil
end

Pair this with server-side prerequisite checks inside your purchase handler so a client cannot fire BuyUpgrade("Tier3Laser") without owning Tier2Laser.

3. Session-Locking DataStore Profiles Against Server-Hopping Dupes

Even with clean RemoteEvent validation, players can duplicate currency or traded items if Server A saves stale state after Server B has already loaded the profile during a rapid rejoin or teleport.

Use DataStore:UpdateAsync with an explicit SessionLock stamp ({ JobId = game.JobId, LockedAt = os.time() }):

  1. On PlayerAdded: Call UpdateAsync. If another JobId holds a fresh lock (e.g., os.time() - lock.LockedAt < 90), retry with exponential backoff or kick cleanly before mounting player state. Otherwise, claim the lock with game.JobId.
  2. On autosave & PlayerRemoving: Only write if current.SessionLock.JobId == game.JobId, and clear SessionLock = nil exclusively on final release (PlayerRemoving / BindToClose).
  3. Never use SetAsync for profile state: SetAsync blindly overwrites concurrent writes and silently breaks session-lock guarantees.

Interactive Browser Sandbox & Open Resources

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.