Skip to content
GuidesFiveM Server Optimization Guide

FiveM Server Optimization Guide

Performance optimization is essential for providing a smooth experience for players on your FiveM server. This guide outlines best practices, tools, and configuration settings to enhance your server’s performance and minimize lag.


Step 1: Performance Monitoring

Built-in Monitoring Tools

  1. Open the server console and use the following commands:
    resmon         # Basic script performance monitoring
    txAdmin:info   # Server information
    status         # General server status

Using txAdmin

  1. Access the txAdmin control panel.
  2. Check real-time statistics:
    • CPU usage
    • Memory usage
    • Script response times

Using the FiveM Resource Monitor

  1. Enable the resource monitor in the client console:
    resmon true
    The resource monitor displays CPU and memory usage for each resource, helping identify high-usage resources for optimization.

Step 2: Resource Optimization

  1. Remove Unused Resources

    • Delete unused scripts or mods from the resources folder to reduce overhead.
  2. Optimize Scripts

    • Replace outdated or inefficient scripts with newer, optimized alternatives.
    • Consolidate multiple smaller scripts into larger, more efficient ones where possible.
    • Use dynamic sleep values in your scripts to reduce unnecessary processing (see detailed Lua example below).

Identifying Problematic Scripts

  1. Use resmon to find resource-heavy scripts.
  2. Pay special attention to:
    • High processing times
    • Excessive memory usage
    • Increased network traffic

Fixing Problematic Scripts

  1. Temporarily disable non-essential scripts.
  2. Update scripts to their latest versions.
  3. Review configuration settings for inefficiencies.

Step 3: Server Configuration Adjustments

  1. Open your server.cfg file and adjust settings for better performance:

    sv_maxclients 64  # Limit the number of players to match your server's capacity
    sv_scriptHookAllowed 0  # Disable ScriptHook
    sv_enforceGameBuild 2802  # Set a specific game build version
  2. Disable unnecessary logging:

    set mysql_debug false
    set txAdminMenu false

OneSync Settings

onesync on             # Enable OneSync
onesync_population true # Improved entity management

Step 4: Database Optimization

MySQL Maintenance

  1. Run regular table optimization:
    OPTIMIZE TABLE table_name;
  2. Remove unnecessary old data.

Using Indexes

  1. Add indexes to frequently used columns:
    CREATE INDEX idx_name ON table_name (column_name);
# MySQL settings
set mysql_connection_string "mysql://user:password@localhost/dbname?waitForConnections=true&connectionLimit=10"
set mysql_slow_query_warning 200
set mysql_debug false

Step 5: Caching and Compression

  1. Enable Caching

    • Use a caching solution to minimize loading times for assets like textures and models.
  2. Compress Resources

    • Compress large files (e.g., .ytd or .ydr) to reduce resource size and improve loading speeds.

Step 6: Regular Maintenance and Monitoring

  1. Use third-party tools like txAdmin to monitor performance metrics and troubleshoot issues.
  2. Regularly update resources to their latest versions.
  3. Check server logs for recurring errors or warnings.

Step 7: Lua Script Optimization Example

Guide to Optimizing FiveM Threads in Lua with Dynamic Sleep Values

When creating scripts in FiveM using Lua, optimization is key to ensure smooth performance. A common scenario involves using while true do loops for periodic updates, which can be resource-intensive if not handled properly. Here’s a step-by-step guide on how to optimize threads using distance checks and dynamic sleep values.

1. Understand the Problem

The while true do loop runs continuously, and without optimization, it consumes unnecessary resources. By dynamically adjusting the sleep time based on proximity or activity, you can reduce the script’s impact on performance.

2. Set Up the Loop

Start by creating the thread with Citizen.CreateThread. Within this thread:

  • Obtain the player’s ped (player character).
  • Get the coordinates of the ped.

Example:

Citizen.CreateThread(function()
    while true do
        local ped = PlayerPedId()
        local pedCo = GetEntityCoords(ped)
        local sleep = 1000 -- Default sleep time

3. Iterate Over Locations

Assume you have a table of locations (e.g., Config.Locations) where some action occurs:

  • Use a for loop to iterate through these locations.
  • Calculate the distance between the player and each location.

Example:

        for locationName, locationData in pairs(Config.Locations) do
            local placeDist = #(pedCo - locationData.pos)

4. Set Dynamic Sleep

  • If the player is far away from all points of interest, maintain a high sleep value (e.g., 1000 ms).
  • If the player is close to a specific point (e.g., within 1.2 units), reduce the sleep time for faster updates (e.g., 7 ms).

Example:

            if placeDist <= 1.2 then
                sleep = 7 -- Faster updates
            end
        end

5. End the Loop with Wait

After checking all locations, use Citizen.Wait(sleep) to pause the loop dynamically. This reduces the script’s load by only updating as needed.

Example:

        Citizen.Wait(sleep)
    end
end)

Full Example Code

Citizen.CreateThread(function()
    while true do
        local ped = PlayerPedId()
        local pedCo = GetEntityCoords(ped)
        local sleep = 1000 -- Default sleep time
 
        for locationName, locationData in pairs(Config.Locations) do
            local placeDist = #(pedCo - locationData.pos)
            
            if placeDist <= 1.2 then
                sleep = 7 -- Faster updates when nearby
                -- Intensive code here like drawing UI elements
            end
        end
 
        Citizen.Wait(sleep)
    end
end)

6. Benefits of This Approach

  • Performance Optimization: The script only runs intensive updates when the player is close to a relevant location.
  • Reduced CPU Usage: Dynamic sleep values prevent unnecessary iterations.
  • Smooth Gameplay: Players won’t experience lag due to inefficient threads.

Step 8: Hardware and Hosting Recommendations

  1. Ensure your hosting provider meets the recommended specifications for FiveM:

    • CPU: High single-thread performance.
    • RAM: At least 8GB for small servers, more for larger ones.
    • SSD Storage: Faster storage reduces loading times.
  2. Consider upgrading your plan if player counts frequently max out.


Final Tips

Security and Performance

  • Enable DDoS protection through your hosting provider.
  • Limit the number of connections per IP.
  • Set up a queue system for peak hours.

Ongoing Maintenance

  • Regularly review and update scripts.
  • Monitor resource usage over time.
  • Document changes and their performance impact.

Remember: Optimization is an ongoing process. Regular checks and improvements will help maintain optimal server performance.