Datastore Caching Module

Hello programmers! I was working on a game project, and I made this module for optimizing the Datastore queues, so it won’t fill up as much.

It’s a ModuleScript with an API for caching Datastore values before publicly getting them.

Here’s a link, before I get to the examples:
https://www.roblox.com/library/4049083273/DataStoreCache

If you have any suggestions, feedback, etc. let me know. It helps a lot :heart:

Quick Documentation

DataStoreCacheModule.new(name [, scope]) - Returns a new DataStoreCache instance that shares the API.

DATASTORECACHE METHODS
DataStoreCache:set(key, value) - Sets the value of the key.
DataStoreCache:get(key) - Gets the value assigned to the provided key. If it doesn’t exist in the cache, then it’s ripped from the DataStore then cached.
DataStoreCache:flush(key) - Saves the value assigned to the provided key to the DataStore.
DataStoreCache:flushAll() - The same as :flush() but it flushes all keys to the DataStore, so you don’t need to provide a key.

Player join/leave implementation

In a Script, inside of ServerScriptService, the module is in the modules folder: ServerScriptService.Modules

local players = game:GetService("Players")
local DataStoreCache = require(script.Parent.Modules:WaitForChild("DataStoreCache"))

local datastores = {}

players.PlayerAdded:Connect(function(plr)
    local datastore = DataStoreCache.new(plr.UserId .. "_save")
    datastores[plr.Name] = datastore
    
    local save = datastore:get("save")
    if(save ~= nil) then
        -- Do whatever happens when a player has a save.
    else
        -- Give the player a save.
        save:set("save", 0)
    end
end)

players.PlayerRemoving:Connect(function(plr)
    local datastore = datastores[plr.Name]
    
    -- Save to the datastore.
    save:flushAll() -- Since there's one value, it shouldn't overflow the DataStore's limits.
end)

If you get it, please leave feedback, it’ll help me improve my code in the future and it’s just overall helpful. If you make anything with it, link it! I’d love to see what you make with it.

8 Likes

Handy dandy, thanks!
So flush is what actually saves the data?

1 Like

Yes. You can use flushAll() to save all keys.

I’m working on an update to make it more secure right now, actually. Happy coding! :grin:

Ok, so after reviewing the module I noticed some flaws still, hopefully you can take advantage of this information :wink:

When data is flushed, but still fails, there could be a huge data loss (depending on data saved).
I recommend you cover your SetAsync in pcall, and make a system that retries a flush multiple times if it fails.

Hope it helps!

Note: You may also not want this under #development-support . Put it under #development-resources

1 Like

I know, it was an accident. :neutral_face:

I had updated the module yesterday to do this, I also made an updated topic about it: DataStoreCache Update - Safer Data Saving!

2 Likes