Guides · Engineering
Using a database in a Minecraft plugin without lagging the server
Load and save player data from MySQL or SQLite off the main thread, with a connection pool, a cache, safe shutdown saves and errors you can see.
Almost every plugin that stores player data ends up with a database: SQLite for small servers, MySQL or MariaDB for networks that share data between servers. And almost every one of them, at some point, freezes a server because a query ran on the main thread.
A tick has 50 ms. A query to a MySQL server in another data center can take 20 to 100 ms on a good day and seconds on a bad one. While it waits, nothing else on the server moves.
This guide covers the pattern that avoids it: a connection pool, I/O off the main thread, a cache in between, and saves that don't get lost on shutdown.
The rule
The main thread never waits for the network or the disk. Every query, every file read and every HTTP call goes to another thread, and only the result comes back.
The other half of the rule is just as important: the Bukkit API is not thread-safe. From an async thread you can run SQL, parse results and build plain Java objects. You can't touch players, worlds, entities, inventories or scoreboards. Those changes go back to the main thread.
A connection pool
Opening a JDBC connection per query is slow, and sharing one connection between threads breaks. A pool keeps a few connections open and hands them out. HikariCP is the usual choice:
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + database);
config.setUsername(user);
config.setPassword(password);
config.setMaximumPoolSize(4);
config.setPoolName("arenaplus");
HikariDataSource dataSource = new HikariDataSource(config);
A Minecraft plugin rarely needs more than a handful of connections; a big pool just holds connections open on the database server for nothing. Close the pool in onDisable.
Shade HikariCP into your jar and relocate it. Another plugin with a different Hikari version in the same package is a classic source of NoSuchMethodError at startup. Shading and relocating
For SQLite, a pool buys little: SQLite allows one writer at a time. Use a single connection behind a single-threaded executor, so queries run one after another off the main thread and never fight over the file.
Off the main thread, and back
The simplest version uses the Bukkit scheduler:
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
Stats stats = storage.load(uuid); // async: SQL only
Bukkit.getScheduler().runTask(plugin, () -> applyStats(player, stats)); // main thread
});
As soon as you have more than a couple of these, give storage its own executor and return futures. It keeps threading decisions in one class instead of spread across every listener:
private final ExecutorService executor = Executors.newFixedThreadPool(2);
public CompletableFuture<Stats> load(UUID uuid) {
return CompletableFuture.supplyAsync(() -> query(uuid), executor);
}
storage.load(uuid).thenAccept(stats ->
Bukkit.getScheduler().runTask(plugin, () -> applyStats(player, stats)));
Check that the player is still online when the result arrives: they may have left while the query ran.
On Folia, Bukkit.getScheduler() throws. Run queries on the async scheduler and come back with player.getScheduler(). Folia compatibility
Load on join, read from memory
The worst pattern is a query every time a value is needed: on each kill, each block broken, each placeholder refresh. Load a player's data once, keep it in memory while they're online, and read from there.
AsyncPlayerPreLoginEvent is the right place to load. It runs on its own thread before the player joins, so it can wait for the database:
private final Map<UUID, Stats> cache = new ConcurrentHashMap<>();
@EventHandler
public void onPreLogin(AsyncPlayerPreLoginEvent e) {
try {
cache.put(e.getUniqueId(), storage.query(e.getUniqueId()));
} catch (SQLException ex) {
e.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, "Couldn't load your data, try again.");
}
}
When the player joins, the data is already there. If loading fails, refusing the login is better than letting the player in with empty stats that will be saved over their real ones.
Saving without losing data
Saves are where data goes missing.
- Save on quit, async. Take a copy of the data on the main thread, then write it on the storage executor. Remove it from the cache only after the write finished.
- Save periodically. Every few minutes, write what changed. A crash then loses minutes, not a whole session.
- Save synchronously in
onDisable. When the server stops, scheduled tasks are cancelled and the JVM may exit before your async writes finish. InonDisable, write everything that's still dirty directly, then shut down the executor and wait for it, then close the pool. A slower shutdown is fine; a lost inventory isn't. - Batch writes. Saving 80 players one statement at a time is 80 round trips. A prepared statement with
addBatch()andexecuteBatch()is one.
Make database errors visible
A database problem on a server you've never seen usually arrives as a vague review: "stats reset", "data doesn't save". By then the logs are gone.
With PluginAnalytics, exceptions that go through your code are captured from every server automatically, grouped by stack trace, with IPs, UUIDs and credentials in URLs removed. For errors you catch and handle yourself, report them so they don't disappear:
try {
storage.save(uuid, stats);
} catch (SQLException e) {
analytics.captureError(e);
getLogger().warning("Couldn't save stats: " + e.getMessage());
}
Label those issues database and you'll see whether one setup keeps failing or many servers share the same problem. Errors
Know which backends servers use
Whether to keep supporting SQLite, MySQL and MongoDB is easier to decide when you know how many servers use each. Config keys containing database are always skipped by the automatic config reading, because they usually hold credentials, so report the backend as a property:
analytics.property("storage", () -> storage.type().name().toLowerCase());
It shows as the share of servers per value, next to your config options. Properties
Check it's really off the main thread
It's easy to think every query is async and miss one: a save in a command handler, a lookup in a placeholder. A profile with spark on your test server finds them while you're looking. Which part of your plugin causes lag
On real servers, the Performance page in PluginAnalytics samples the main thread and shows which of your methods use each tick, by version. Because shaded libraries count as your code, a JDBC call that ended up on the main thread shows up under the listener or command that made it. Performance is part of Premium. To time the queries themselves on any thread, wrap them in a span:
Stats stats;
try (PluginAnalytics.Span span = analytics.time("stats_load")) {
stats = query(uuid);
}
Checklist
- No query, file read or HTTP call on the main thread, and no Bukkit API on async threads.
- One pool (HikariCP, shaded and relocated), small; one serial executor for SQLite.
- Load in
AsyncPlayerPreLoginEvent, read from memory, save on quit and periodically. - Save synchronously in
onDisable, then close the executor and the pool. - Errors you catch are reported, not just logged.
More guides
Which part of your Minecraft plugin causes lag (and how to fix it)
Find the part of your Spigot or Paper plugin that causes lag: MSPT, spark profiles, the usual suspects and how to see its cost across all servers.
4 min readEngineeringHow to make your Minecraft plugin Folia-compatible
Make your plugin Folia-compatible: folia-supported, the right Paper scheduler for each task, one jar for Spigot, Paper and Folia, and pitfalls.
3 min read