Performance tips (network bandwidth, client framerate, etc.) for custom NPC replication

This post was last updated on 2/1/2026.

Better optimizations may be found in the future. If you have any in mind, please tell me, I’ll attempt to update this post (no guarantee).

Performance tips (network bandwidth, client framerate, etc.) for custom NPC replication

Heya! This serves as a compilation of tips and tricks I’ve learned from my research on custom NPC replication. Originally a comment on a thread, but I decided to post and extend it.

For context, what I refer to as “custom NPC replication” is:

  • Pathfind + send position data for NPCs on server (rather than placing actual models and humanoids and letting Roblox handle the replication)
  • Render position data for NPCs on client
Why would one develop their own replication system?

Now without further ado, let’s begin.


Limiting how often you send data + client interpolation

The rule of thumb is you should only send necessary data, when it is necessary.

Realistically, you don’t need to (and shouldn’t) send data every frame. A common rate is sending data every 1/10th of a second, or basically 6 :FireAllClients() every 1 second. Do note that there is no one-size-fits-all update rate, test out different values and see what fits with your game’s needs.

Assuming you’re using .Heartbeat, limiting your data could look like this:

local counter = 0
RNS.Heartbeat:Connect(function()
	if counter < 10 then
		counter += 1
		return
	else
		counter = 0
	end
	
	-- send position data to clients
end)

Furthermore, you should only send out position data (server) and render models over that position data (client) of NPCs that have changed positions. This should save up network bandwidth for other replicated objects (parts, animations, etc.)

Now once the client receives this data, you can then interpolate each NPC towards each position. It can look like this:

local npcHRP: CFrame = ...
local positionData: CFrame = ...

npcHRP.CFrame:Lerp(positionData, .05)

I also recommend changing the value of the interpolation through deltaTime (assuming you’re rendering with .RenderStepped) to account for FPS spikes or framerates beyond 60 FPS.

local deltaTimeConverted = deltaTime / (1 / 60)

npcHRP.CFrame:Lerp(positionData, .05 * deltaTimeConverted)

Compressing your data before sending

We can further improve network bandwidth by decreasing (compressing) the amount of bytes our data holds. Same rule of thumb as above applies here; only send what is necessary. Now when it comes to networking, you need to think in terms of bits and bytes:

  • A bit is either 0 or 1
  • A byte has 8 bits
  • A kilobyte has 1000 bytes or 8000 bits

For a general guideline for data types and their equivalent bytes (and networking in general), read this post by @PysephDEV, very helpful. The numbers of bytes that I will mention will mostly come from the post, but anyways…

Side note,

The resource has some outdated information (e.g. string byte size), you can look into this .luau file on Github, also made by @PysephDEV.

First tip, always use arrays over dictionaries. Dictionary (non-integer) indexes just cost you extra bytes and aren’t necessary. Here’s an example:

-- instead of ~28 bytes
local data = {
	-- "CFrame" -> ~8 bytes
	-- CFrame.new() * CFrame.Angles() -> ~20 bytes
	CFrame = CFrame.new() * CFrame.Angles()
}

-- reduce to ~20 bytes
local data = {
	-- CFrame.new() * CFrame.Angles() -> ~20 bytes
	CFrame.new() * CFrame.Angles()
}

Second tip, if you’re sending out CFrame’s, you can compress its position and rotation components. There are many ways to do this, but here are some common ones:

As a reminder:

  • CFrame takes up ~20 bytes
  • Vector3 uses 32-bit (4-byte) floats per coordinate, taking up a total of ~12 bytes.
  • Vector3int16 uses 16-bit (2-byte) integers per coordinate, taking up a total of ~6 bytes. It’s range is [-32768, 32767]
  • Numbers use 64-bit (8-byte) floats, taking up ~8 bytes (regardless of whether its 1, 1.000001, or 100000)

The first way is to convert your CFrame into two Vector3int16.new(), it can look like this:

Side note,

If you’re working with radians which you most likely are, keep in mind that Vector3int16 uses integers only.

To make sure your radians (which have a range of [-3.14, 3.14] or [-math.pi, math.pi]) stay intact, I recommend multiplying them by 10 as you insert them in a Vector3int16.new() and dividing by 10 (or multiplying by .1) when converting them back into CFrames. I’ll be doing this method below.

local cframe = ... -- ~20 bytes
local rotationX, rotationY, rotationZ = cframe:ToOrientation()
	
-- a total of 12 bytes, drastic improvement from 20 bytes!
local position = Vector3int16.new(cframe.X, cframe.Y, cframe.Z) -- ~6 bytes
local rotation = Vector3int16.new(rotationX * 10, rotationY * 10, rotationZ * 10) -- ~6 bytes

-- converting position and rotation back into a cframe can look like this!
local newCFrame = CFrame.new(
	position.X, 
	position.Y, 
	position.Z
) * CFrame.Angles(
	rotation.X / 10, 
	rotation.Y / 10, 
	rotation.Z / 10
)

The second way is to further compress your position and rotation via Vector2int16.new() and numbers.

For position, if you only have one height (Vector3 Y) per coordinate, you can just send out a Vector2int16.new() instead like so:

Side note,

For those wondering how the client could get the Y coordinate, you can look into height maps like in this post by @Atrazine. Big credits to this post, genuinely super helpful.

-- old
local position = Vector3int16.new(cframe.X, cframe.Y, cframe.Z) -- ~6 bytes

-- new, let the client handle the Y (e.g. through height maps)
local position = Vector2int16.new(cframe.X, cframe.Z) -- ~4 bytes

For rotation, usually it’s safe to assume that only the Y axis (e.g. turning left to right) is changing, so we can just send the Y axis.

Now keep in mind that numbers are 64-bit (8-byte) floats, which is why we should compress the rotation even further through the buffer library. In the example below, I compress rotation into a 16-bit (2-byte) integer:

-- old
local rotation = Vector3int16.new(rotationX * 10, rotationY * 10, rotationZ * 10) -- ~6 bytes

-- normal numbers
local rotation = rotationY * 10 -- ~8 bytes

-- compressed numbers through buffer library
local rotationBuffer = buffer.create(2) -- a size of 2 bytes for 16-bit number
buffer.writei16(rotationBuffer, 0, rotationY) -- ~2 bytes

-- getting back the number is as easy as
local receivedRotation = buffer.readi16(rotationBuffer, 0)

Batch CFraming for rendering NPCs

Even with good network bandwidth, your clients can still lag if there are too many units being CFrame’d every frame (render step.)

A method to improve client performance is :BulkMoveTo() which allows you to set the CFrame of parts in a single batch. This is more performant than individually setting each NPC’s CFrame through a loop because the function runs directly on C++ and optimizes other things behind the scenes. To quote its documentation,

This function moves a table of BaseParts to a table of CFrames without necessarily firing the default property Changed events. This provides a very fast way to move large numbers of parts, as you don’t have to pay the cost of separate property sets for each individual part.

By default, the Changed event of each part fires for Position, Orientation, and CFrame. However, if you specify FireCFrameChanged as the third argument, only the Changed event for the CFrame property will fire.

https://create.roblox.com/docs/reference/engine/classes/WorldRoot#BulkMoveTo

Here’s an example of how you could implement it into your code:

-- instead of rendering npcs like this
for i,v in npcList do
	local npcPart = ...
	local npcCFrame = ...

	npcPart.CFrame = npcCFrame
end

-- you can use this instead
workspace:BulkMoveTo({npcPart1, npcPart2, ...}, {npcCFrame1, npcCFrame2, ...}, Enum.BulkMoveMode.FireCFrameChanged)

Just a reminder that Enum.BulkMoveMode.FireCFrameChanged will reap the most performance benefits (as explained in the documentation above), so always use it for the third parameter.

Implementing render throttling for large amounts of NPCs

To repeat what was said above, sometimes the network bandwidth isn’t the limiting factor, but the rendering itself. When you are CFraming NPCs in the four digits (1000+), you are may be experiencing unstable framerates, especially on lower-end devices.

Instead of rendering all NPCs per frame (render step,) you can divide it into smaller batches and alternate between them. To give an example:

  • Rendering 1000 units in a single frame
  • Rendering 500 units for a frame, rendering the other 500 units for the next -----> 50% workload reduction per frame
  • Rendering 250 units for a frame, rendering the next 250 units for the next, and so on and so forth -----> 75% workload reduction per frame

Do keep in mind that because you aren’t rendering every NPC at every frame, NPC movement can look choppy (not by much, but it can still be noticeable). This choppiness can be decreased by how you will divide your batches, but not completely removed. This should only be a last resort.

Here’s an example on how you could do it (assuming you use:BulkMoveTo(), but you can adapt it to your own system):

local npcRenderThrottle = 300
local queueData = {}

--[[
this example assums your data and queueData are arrays
and that the values of the arrays are also arrays where the actual data is stored

e.g. data = {
	{npcPart1, cframe1}
}
]]
RNS.RenderStepped:Connect(function() 
	local npcList = {}
	local cframeList = {}
	local isQueueAvailable = #queueData > 0
	
	-- data refers to the actual position data you get normally
	for i,v in (isQueueAvailable and queueData or data) do -- uses queueData when available, otherwise, uses data
		local npc = ...
		local cframe = ...
		
		if isQueueAvailable then -- if there is queue however.. focus on getting rid of that first
			table.remove(queueData, table.find(queueData, v))
			table.insert(npcList, npc)
			table.insert(cframeList, cframe)
		else
			if i > npcRenderThrottle then -- above throttle? add to queue
				table.insert(queueData, ...) 
			else -- otherwise, just add npcList and cframeList
				table.insert(npcList, npc) 
				table.insert(cframeList, cframe)
			end
		end
	end
	
	workspace:BulkMoveTo(npcList, cframeList, Enum.BulkMoveMode.FireCFrameChanged)
end)

Pathfinding via flowfields (flowfield pathfinding)

This isn’t specific for custom NPC replication, but for games with a ton of NPCs in general.

Roblox pathfinding, at least from what I understand, creates a NavMesh and uses A* to traverse through. It’s very good for generating accurate(ish) waypoints in dynamic environments. However, it is computationally expensive.

In comparison, flowfield pathfinding runs on the principle of “calculate a path once, reuse for all NPCs.” This allows for the pathfinding of hordes of NPCs with little performance cost.

In simple terms, it creates a grid and calculates a direction for each cell, where all cells eventually flow into the target position.

This means that NPCs can pathfind using the same flowfield from any position. And you only need to recalculate whenever the target(s) have changed positions or the environment has changed.

Side note,

If you’re looking for a module to generate performant flowfields (with chunk pruning optimizations), you can try FastFlow by @bob_factory, very pleasant to use.

It pathfinds on a 2D grid by default, but if you’re looking on how to implement flowfields with 3D grids / maps, you can read this post by @happya_x.

Honorable mentions

Multithreading / parallel luau

You can look into multithreading / parallel luau via Actors, but there’s honestly not much you can do with it besides split up calculations on the server (you can’t render in parallel unfortunately, setting CFrames is not parallel safe.) Here are a few notes on it:

  • You’re recommended to use 32-64 Actors; too little and you won’t see much effect, too much and it’ll be hard for Roblox to distribute all the workload
  • Avoid long and time-consuming computations for Actors, more detail can be found on this part of the documentation
  • Further best practices can be found here

Important side note,

At the time of writing this, the client has been capped to 3 total parallel threads due to design limitations. I believe it’s currently being worked on, but unfortunately, there is no apparent timeline on when it will be fixed.

Native code generation

You can also look into applying native code generation via @native on your server calculations (e.g. compression with buffer library), theoretically speaking you’re trading CPU performance for memory. There’s no guarantee for better performance though, so use the ScriptProfiler to see if it makes a difference. Further best practices can be found here.

Networking libraries

And yeah, I should address networking libraries. If you’re interested in decreasing your network bandwidth even further, networking libraries aim to reduce the overhead of RemoteEvents (~9 bytes per RemoteEvent fired). This reduction is a big difference in overall network bandwidth, and it really shows when you go past 1000+ NPCs. There are many networking libraries released to DevForum, so do your research.

From what I understand, they mostly work by batching multiple RemoteEvents into one RemoteEvent + compressing the data passed through (e.g. with buffers.) For more details, this post by @Content_Corrupted019 has a very detailed explanation on how it works.

External resources

Lastly, I recommend reading these posts as well, they were extremely helpful for my research:

49 Likes

Very nice guide Downrest! Very valuable information

2 Likes

Oh hey it’s the man himself! Thank you, glad you found it informative, means a lot.

Hope it was readable, tried to write straightforward.

1 Like

Making a system like this is so much fun, another useful post for those trying to reduce their bandwidth usage is this one which has been so helpful for reducing my Network Recv massively:

4 Likes

Be careful how you use buffers
Bit packing in most cases is superior.
Buffer has 9 bytes of overhead on Roblox (8 byte integer telling the length + 1 byte type signature).

While if you only use numbers with bit packing, it will be 9 bytes as a whole without extra allocated bytes as you may do with a buffer.

Allocating 2 bytes = waste 100% (11 bytes total)

1 Like

Oh hey! That’s a lovely post by the way, thanks for replying.

I checked it out and, surprisingly, it practically uses the same techniques I’ve researched and included in this post.

The most apparent thing is his claim of being able to handle 10K+ positions under 50 KB/s, I’ve been working on my own replication system (that uses Roblox’s RemoteEvents) and it peaks at 120 KB/s when handling only 2K positions. This is such an absurd difference that it makes me realize just how big of an effect it could be to use networking libraries for compression, though for my usecase, I won’t probably go over 500 positions which takes about ~25 KB/s.

I just mentioned these libraries in “Honorable Mentions” but I might have to actually giving it its own individual part for this post! I’ll see what I can do.

Oh yeah I’ve heard of that before, I should probably look into that (no guarantee though, only made this post on my freetime). Thanks!

1 Like

Don’t just research on devforum how to optimize bandwidth, but research in real-world optimizations

First, you must considering what type of NPCs you about to make, if it is not about zombies, RTS NPCs or NPCs that they change very common, it’s would be static NPCS ( NPCs without their unique identities )

So I tried to make an obby with large amount NPC, like about 500-700, if they dies, they just spawns back to their checkpoint after 1 seconds, BUT THE BANDWIDTH ARE DEVIOUS.

So I would make a animation replication first, but you need to somehow remove the NPCs replication to client without remove the roblox physics. We can put them in the server CurrentCamera, boom it works!

NOTE: Physics in the Roblox’s server aren’t the same as the Studio’s server. So for real performance testing, I always do in actual RobloxPlayer to test it

Animation replication would be easy of this part, we have 6 states needed only for replications:

  • Walk
  • Idle
  • Jump/Fall ( Almost same animation who cares )
  • Climb
  • Ragdoll/Death ( Like could be break joints )
  • Teleport ( special one, so we don’t need to lerp NPC cframe, it won’t change animation, just remove lerping, like for falling down the void, or teleporting )

But the main question, how can we pack it?

  1. Bit packing ( 3 bit per state )?
  • A good old method, the easiest one of them, 500 NPC per 3 bits, → 1500 bits → ~188 bytes, would be so big if we sent it with 20hz, that would be pretty pretty bad
  1. Using Zstandard ( in-buffer itself either EncodingService )?
  • Noo… It almost impractical to get matches from a random data like this??? Because its primary codec are LZ being compressed with Huff0 and FSE, compress worst than bit packing itself
  1. Saying of FSE, How about of an entropy coding?

So we found the key for animation, but how about the rotation and the position?
For now, NPC don’t need the rotation roll and pitch expect yaw ( for NPC looks, like simulate NPC shiftlock without it being weird )

  1. Using bit packing again?
  • Easy but NOT RECOMMENDED, they are good, but inflexible, like imagine a obby thoudsands of studs. A tower, a simulator, a battleground, IT’S SO LIMITED!!!
  1. Using variable-length integers combine with Zigzag, or more modern one VLQ.
  • More flexible, unlimited size of map, but less effecient, this combines with Zstandard would make a good combo!

But what we forgot??? The more NPC go further, the more byte is it, that VERY BAD? How can wwe fix it? Ahha! We can use Delta encoding!

But how we do it? So we need a small demonstration about how it works exactly?

  • We can get the deltas with old_x, old_y, old_z, old_r - new_x, new_y, new_z, new_r, pretty classic. However how can we sent the clients? like if a player joins, when sent deltas. make it different and weird for all client, some NPC on top, some on the void. THAT’S SO HA…

  • But don’t worry, we have a solution, when the player joins, we sync the Absolute position and rotation of the NPC to the client, that would make every clients look the same.

  • BUT THERE’S A BUG, sometimes when looping Update, The client recieves the Update results before the sync results, make bad-wifi players looks the NPCs go through the walls.

  • WE CAN FIX IT, you can make a query systems. Make 2 remote events, 1 for Update, 1 for Sync, if updates before syncs, so they put into a table for futures uses, after sync, runs all of it one by one! Now 20000+ ms ping players is equal <15 ms players.

That’s the hardest part so far, takes me like hours to make it work. With this, we can’t bitpack them anymore but we can only uses something like Varint or… Elias Gamma coding!!!

  • We found a new algorithm for THIS! so our data only about 1 - 12 so it won’t be that big compares to Varint. it’s like a bit-based varint, but it fails for big data like 15+ ( wasted >1 bytes )

  • But we can uses rANS for this too, but rotation being sooo random ( NPC being rotates 180 degrees everytime they turns )

  • Uses Uniform Scalar Quantization, rounding numbers instead of 1.23012312…, We only need like 0.2 studs precision for X, Y, Z and 10 degress precision for rotation. A BIG improvement with no differences!

We only need Elias Gamma + Zstandard in the builtin-buffer for now! it compress alot now.
With these optimizations, runs 20hz ( 0.05 seconds per sent ) with 500 NPCs. It will gets us as small as …

Only … ~20+ KB/s ??? That’s so big “for me” compare to other game…

And also, it looks very jiggy too. How can we fix it?

  • 4 frame lerping, everytime it updates, it will lerp the NPC 4 inbetween frame. This will make the NPC like actual real NPCs.

WE NEED TO COMPRESS MORE AND MORE PERFORMANCE:

  • Uses delta-of-delta, getting delta of delta itself. So it like getting the previous delta - new delta. That take me like days to figure out and make it work. It just like cherry on top, 1.5x compression boost. 20KB/s → ~12kB/s

  • Don’t uses BulkMoveTo, it uses like 20% script activity, after alot of researching, we can uses Motor6D.Transform, makes it only ~7% Activity! YES WE DON’T NEED TO MAKE A SKINNED MESH VERSION OF IT! It seems normal in Studio, but on RobloxPlayer, it seems very buggy ( rendering issues I think ), I will make a bug report for it if possible

  • Parralel luau could improves performances, but I don’t know how to split it either

Some NOTES in the future. This could improve network bandwwidth, but haven’t tested.

  • Splits X, Z / Y / R into 3 buffers, X, Y, Z compress with rANS. R compress with Elias Gamma
  • Could add some preprocessor like Context Modeling ( too complex ) or MTF ( could be worst )
  • buffer.tostring before sent, haven’t tested. It could be bigger idk.

If I am not wrong, Actor creates whole new environment differs from current environment.
It would increase memory like crazy ( could even crash in low-ram devices )

4 Likes

Brilliant post, thank you so much for spending the time to write this all.

I will take this to heart for sure. I’ll try researching about the compression methods you mentioned, so if I feel like updating this post (or maybe even make a seperate one all about network bandwidth compression), I’ll be able to give a straightforward and detailed explanation for it. Though I only do programming stuff on my freetime, so shrug, I’ll have to see.

I just want to say that the server CurrentCamera method of skipping replication is such underrated knowledge. I’ve actually thought of simulating physics that way for NPCs but only in theory, very happy to see that somebody actually tried it out!

I might be actually wrong to recommend 32-64 (as 64 is probably only appropriate in specific scenarios that require that many actors), I believe the more appropriate number is 16-32 like what this post by @chess123mate says. Still trying to understand the ins and outs of parallel luau, so there’s room for learning.

All I understand is that Roblox automatically distributes each environment to the client’s device cores, I have no clue on it’s exact effect on memory though. To quote another post (from the same thread),

I can probably find something in the post announcing parallel luau, but for now, I have no answers.

My first update!

Was working on my own replication system and had optimal network bandwidth, but I was experiencing low framerates for 1000+ NPCs. Decided to add a sort of render throttling system where instead of every NPC being rendered every frame, I divide the NPCs into smaller batches and let them be individually rendered by their own frame.

If anybody is interested in reading, I added this as another part of this post. Just came up with the idea right now and it actually worked, don’t think anybody else has talked about a method like this (at least from my knowledge?) For reference, I went from ~30 FPS with 1000 NPCs to ~60 FPS with each batch being roughly ~333 NPCs.

Thanks. This is very valuable information. I’ve recently started getting more into performance, data management, etc, and this has helped me a lot with many concepts I was not aware of, even tho I’m not really making a custom NPC system.

1 Like

Glad it could help, thanks for reading! There’s so much magic to the world of performance and data compression, hope you learn more things along your journey. I recommend engaging with resources (such as developer conference videos) outside of DevForum as well.

I myself also have so much more to learn.

1 Like

I am still learning optimization, and this is very useful. Thank you so much!

(didn’t check the date of this post, oops)

1 Like

I don’t know much about ByteNet, but an alternative, underrated, and probably more powerful SerDes + compression library I know of is Squash. It uses cursor pointers, records (w/ schemas), VLQs, etc. to partially automate and reduce payload sizes in packets. It’s more useful with a larger quantity and variety of data because obviously buffers are faster than strings because they don’t duplicate when modified and records let you SerDes complex objects like nested tables with a single function call. You could include this in your optimization guide if you wanted, but it might be overkill if you’re just sending a CFrame or something like that. Roblox already does a good job optimizing those, and a few bytes pales in comparison to modern bandwidth or the capacity of a single packet (~700 bytes) for that matter.

1 Like

Oh yeah! I’ve seen that documentation page before, looks very interesting. Dynamic buffers… very interesting system.

Both Squash and this post use buffers to compress data, though it does bitpacking which I haven’t covered yet. Overall, it’s a good read and I’d recommend anybody to look at their documentation, also has some good technical information.

Haven’t ever used Squash, but it could be something really cool, maybe I’ll check it out in the future? Thanks for commenting.

1 Like

Been working on this for the past week, thanks to this post and some other resources i managed to pull it off.

1 Like

Two things i want to add to this post:

-If your game is going to be renewing the enemy pathfinding constantly (e.g. PvE), limit how often you do the renewing (similar to limiting how often you send data) and don’t pathfind when you don’t need to like when the enemy has a straight path to the player.

-You can use “Render Distance” with “Render Throttling” to increase client performance even more (if an enemy is outside that render distance, they wont be rendered at all).

Code sample from my system:

local RENDER_DISTANCE = 250 -- in studs
local Cushion_Zone = 20 -- in studs, to prevent flickering of enemies on the edge of the render distance

--In my system, this is done in a for loop inside a .Heartbeat
if camPos then --I recommend using the camera, but you can also use players character.
    local pos  = --Enemy position here
    local dist = (pos - camPos).Magnitude

-- Check if the enemy model exists before attempting to un-render
    if enemyModels[id] then 
        if dist > RENDER_DISTANCE + Cushion_Zone then
            UnRenderModelForEnemy(id)
        end
 -- No enemyModel? check if the enemy is inside the render distance before rendering the model.
    elseif dist <= RENDER_DISTANCE then
        RenderModelForEnemy(id)
    end
end
2 Likes