← Devlog

FiveM performance: finding what lags, from resmon to the server profiler

Find out why a FiveM server lags with the tools FiveM ships: resmon, the profiler, hitch warnings, state bags, events and the database.

“The server lags” is a symptom, not a diagnosis. It can be the player’s PC, their connection, the server, a script on either side, the database or the assets the game has to stream. The fix for one does nothing for the others, so the first job is to find out which one it is.

This guide covers the tools FiveM ships for that, and the problems that show up again and again on large servers. It applies to FiveM as most servers run it today (FXServer on GTA V Legacy); the new GTA V Enhanced version changes some tools.

First, where does it lag?

  • Everyone at the same moment (rubber-banding, actions that answer late): almost always the server or the database.
  • One player, or one place: the client. Their hardware, the scripts running near them or the assets around them.

On the client, cl_drawperf true shows FPS, ping, packet loss, CPU and GPU on screen, and netgraph true shows network traffic. High ping or packet loss is a network problem no script change will fix.

resmon: what client scripts cost

resmon true in the client console (F8) opens the Resource Monitor: CPU time per resource in milliseconds, memory and streaming. Three things to know:

  • It is an average of the last 64 ticks, and on the client a tick is a frame. A script at 0.01 ms that takes 5 ms once a second still causes a stutter, and resmon will look clean.
  • It only shows the client. Server scripts do not appear.
  • FiveM warns players when a resource averages more than 6 ms, naming it on screen.

A well-written script reads 0.00 ms idle. The exceptions are natives that must run every frame while something is on screen (drawing text or a marker, disabling a control), and only while they are needed. In use, a small number is fine, then back to 0.00 ms. Framework cores and libraries sit higher because they work for every other resource; what matters is that their number is stable. Check in busy places: a script at 0.00 ms in an empty field can read 0.30 ms in a crowd.

The profiler: which function, and when

resmon tells you which resource. The profiler tells you which function, and shows the spikes the average hides:

profiler record 500
profiler view

record takes a number of frames and view opens a timeline in a Chrome DevTools viewer. profiler saveJSON file.json keeps it to compare before and after a change. The same commands work in the server console, where they count server ticks and print a link to open. Server events, ox_lib callbacks and database waits show up by name.

The server: hitch warnings and txAdmin

FXServer runs three main threads and prints a warning when one takes far longer than its interval:

Thread Runs every Warning
Main (scripts, events) 50 ms server thread hitch warning: timer interval of N milliseconds
Network 10 ms network thread hitch warning: ...
Sync (OneSync) about 8 ms sync thread hitch warning: ...

Server scripts run on the main thread, so a Wait(0) there resumes on the next server tick, about 50 ms later. A couple of warnings at startup are normal; warnings during play are the lag your players describe.

txAdmin charts each thread’s tick times on its dashboard. A healthy server keeps almost every tick in the fastest buckets. Slow main thread ticks at peak hours point to a script or a query; slow sync ticks, to entities and OneSync.

Client loops

The target is simple: almost nothing should run every frame for every player. A server with hundreds of resources can get by with a handful of permanent per-frame loops, such as traffic density; everything else should wait for a distance, a key or an event.

Wait cannot run faster than a frame. FiveM’s documentation is clear that Wait(0) pauses until the next tick, and a thread resumes at most once per tick. Wait(2) is not “500 times a second”: at 60 FPS it is 60, like Wait(0). For less work, wait longer or stop the loop.

Separate the work from the drawing. Finding who is near is expensive and can run every 500 ms. Drawing runs every frame, but only while there is someone to draw:

local nearby = {}

CreateThread(function()
    while true do
        local found, myPed = {}, PlayerPedId()
        local me = GetEntityCoords(myPed)
        for _, player in ipairs(GetActivePlayers()) do
            local ped = GetPlayerPed(player)
            if ped ~= myPed and #(GetEntityCoords(ped) - me) < 25.0 then
                found[#found + 1] = player
            end
        end
        nearby = found
        Wait(500)
    end
end)

CreateThread(function()
    while true do
        if #nearby > 0 then
            for _, player in ipairs(nearby) do
                -- draw the ID for this player
            end
            Wait(0)
        else
            Wait(500)
        end
    end
end)

Create things only near the player. A common mistake is spawning every shop ped, ATM and prop as soon as a player joins. A thread that checks distance every few hundred milliseconds, creates the entity when the player is close and deletes it when they leave fixes it. ox_lib’s points or PolyZone wrap this, but the pattern needs no library.

Natives add up. Every native call crosses from Lua into the game. One PlayerPedId() is cheap; the same call in loops across dozens of resources is not. With ox_lib, cache.ped and cache.vehicle are updated every 100 ms; without it, read the value once per loop and reuse it. ESX and ox_lib each track the player in their own thread, so do not add a third.

State bags instead of event storms

Old scripts often send an event to every player whenever something changes. State bags do this for you: GlobalState for server-wide values, Player(source).state for a player, Entity(entity).state for a vehicle, ped or object. Server-set state replicates on its own, late joiners get the current value, and clients react with AddStateBagChangeHandler.

What bites in practice: every read returns the full serialized value, so do not read big tables in loops; nested writes (state.data.money = 10) do not replicate; clients can write state on entities they own unless you enable sv_stateBagStrictMode; and a client that sends too many updates is dropped. Not for values that change every frame.

Events and their limits

TriggerClientEvent(name, -1, ...) reaches every player. It is right for the weather or a global announcement, and wrong for most other things, like a chat that sends every /me to the whole map. With OneSync the server knows where everyone is, so send to the players near the source.

For big payloads, TriggerLatentClientEvent sends in the background (25,000 bytes per second per player by default) instead of blocking the player’s network channel. In the other direction, the server rate-limits events from each client: a script that fires server events from a loop gets its player kicked with Reliable network event overflow.

KVP for small data

SetResourceKvp and GetResourceKvpString store key-value data without the database. On the client it lives on the player’s PC and suits preferences like a HUD layout, with two caveats: it is keyed by resource name, not by server, and the player can edit it, so never trust it. On the server it is a local store for small resource settings.

The database

Find slow queries first. oxmysql prints any query over a threshold (200 ms by default) with the resource that sent it:

set mysql_slow_query_warning 150

Then look for the usual patterns: one insert per player inside a loop instead of one multi-row insert; one query per row after reading a table (the classic N+1); and updates awaited one by one when a resource stops. And indexes: owned_vehicles.owner is used by dozens of queries on a typical ESX server and often has none.

CREATE INDEX idx_owned_vehicles_owner ON owned_vehicles (owner);

On the server, avoid looking players up one by one. ESX Legacy filters for you, and since 1.10.2 counts by job:

for _, xPlayer in pairs(ESX.GetExtendedPlayers('job', 'police')) do
    -- only the police, in one pass
end

local cops = ESX.GetNumPlayers('job', 'police') -- read from a counter

On QBCore, QBCore.Functions.GetQBPlayers(); on Qbox, exports.qbx_core:GetQBPlayers().

Assets

Streaming is the slowest part of joining a big server, and clothing packs are usually the heaviest part of it. On slow disks, a client can stall long enough on join for scripts’ model requests to time out. FXServer warns at resource start when an asset uses more than 16 MiB of memory, and above 48 MiB adds that it will cause streaming issues: read those warnings, they name the file. On the client, strmem lists streaming memory by asset. Watch for duplicate file names across resources (only one is used), and recompress with care: an aggressive pass saves memory but the quality loss can be visible.

Checklist

  1. Ask for cl_drawperf when players report lag, to rule out the network.
  2. Note every script not at 0.00 ms idle in resmon, in a busy area.
  3. Profile the client where it stutters and the server at peak hours. Look at spikes, not averages.
  4. Check hitch warnings and txAdmin’s thread chart after a busy evening.
  5. Find per-frame loops and server events fired from loops.
  6. Move synced state to state bags and client preferences to KVP.
  7. Set mysql_slow_query_warning and index your slowest queries.
  8. Read the asset warnings at resource start, biggest files first.

Every XeX script is measured this way before release, and its resmon is on its page. If you would rather have someone else go through your server, the Performance & Security Audit profiles it at peak hours and ranks the slowest paths by impact, with the fix for each.