https://slatedb.io logo
we're debugging some really slow DbReader cold sta...
# general
b
we're debugging some really slow DbReader cold starts. Through debugging we saw that the DbReader seems to be reading the full WAL, despite there being compacted SSTs. Here is one manifest. Why is the sequence number from compaction not advancing the replay_after_wal_id which is read during the DbReader startup?
c
@Sujeet's comment is correct: https://discord.com/channels/1232385660460204122/1232385660946616433/1394987409376280619 If the memtable is never flushed, writes will simply continue to go to WAL. You should theoretically hit some backpressure in that scenario eventually. The writes will accrue in the active memtable until it's flushed. So if the memtable flush never happens you should exceed max_unflushed_bytes at some point. As Sujeet suggested, can you provide your full configs for both the writer and reader clients as well?
b
Thanks for your response @Sujeet + @criccomini ! We've updated our config set the l0 size lower, so that we actually get some l0 tables. So it is the default db settings, with
l0_sst_size_bytes = 1048576
. Here's the resolved set afaict: Writer:
Copy code
Settings {
            flush_interval: Some(Duration::from_millis(100)),
            wal_enabled: true,
            manifest_poll_interval: Duration::from_secs(1),
            manifest_update_timeout: Duration::from_secs(300),
            min_filter_keys: 1000,
            max_unflushed_bytes: 1_073_741_824,
            l0_sst_size_bytes: 1024 * 1024,
            l0_max_ssts: 8,
            compactor_options: Some(CompactorOptions::default()),
            compression_codec: None,
            object_store_cache_options: ObjectStoreCacheOptions::default(),
            garbage_collector_options: None,
            filter_bits_per_key: 10,
            default_ttl: None,
        }
Reader is just the default, which resolves to:
Copy code
DbReader {
            manifest_poll_interval: Duration::from_secs(10),
            checkpoint_lifetime: Duration::from_secs(10 * 60),
            max_memtable_bytes: 64 * 1024 * 1024,
            block_cache: default_block_cache(),
        }
c
Gotcha.. is your write pattern a bunch of small writes?
b
From a startup latency we've played around with these overrides:
Copy code
diff --git a/slatedb/src/db_reader.rs b/slatedb/src/db_reader.rs
index 420c483..d004714 100644
--- a/slatedb/src/db_reader.rs
+++ b/slatedb/src/db_reader.rs
@@ -440,14 +440,14 @@ impl DbReaderInner {
         replay_new_wals: bool,
     ) -> Result<(u64, u64), SlateDBError> {
         let sst_iter_options = SstIteratorOptions {
-            max_fetch_tasks: 1,
-            blocks_to_fetch: 256,
+            max_fetch_tasks: 1000,
+            blocks_to_fetch: 25600,
             cache_blocks: true,
             eager_spawn: true,
         };
 
         let replay_options = WalReplayOptions {
-            sst_batch_size: 4,
+            sst_batch_size: 640,
             max_memtable_bytes: reader_options.max_memtable_bytes as usize,
             min_memtable_bytes: usize::MAX,
             sst_iter_options,
basically just trying to overcorrect with some local dev and seeing what performance changes look like
c
I think @Pierre played with some of this a while back as well.. there might be an open PR to make some of these more configurable (I can't remember if we merged it)
b
> Gotcha.. is your write pattern a bunch of small writes? yup write path is basically incremental state storage of a job run. This is being run via a sidecar service collocated with the job. Many small writes that we want to compact together
c
Ya so you could end up with tons of small files which the db reader has to scan over on startup
You could mitigate that by increasing the flush interval to a higher value (to coalesce more writes into a single write batch)
b
and read path is basically loading up the state storage to display in the UI. These are lazy loaded
> You could mitigate that by increasing the flush interval to a higher value (to coalesce more writes into a single write batch) yup, but then I'd expect we would lose out on some durability potentially.
c
Yea, it takes longer to get durability if you increase flush interval
So.. in your case, dropping the L0 max byte size would work.. as you've discovered ๐Ÿ™‚
b
Is there a way to programmatically force compaction maybe? Wondering if we can hook in to something there ๐Ÿค”
Trying to see if we can basically avoid having any WAL upon job completion
c
The problem is compaction only kicks in for data already written to L0
You can disable WAL if you like
There's a feature for that
b
interesting.. at the expense of losing durability?
c
Nope, you will just need to call flush()
If you disable WAL, flush() causes memtables to get flushed to l0
So you can call flush() as you like, which will make the writes durable
b
Oh that's interesting. So we can write all we want, SlateDB will basically assemble memtables in process. And then we call flush when we're happy and that memtable will get written to L0?
c
Yep
Then you'll need need to consider how to best tune your compactor to get those l0's out into higher levels
l0_max_ssts defaults to 8
You might want to drop CompactorOptions.poll_interval quite a bit
And perhaps bump CompactorOptions.max_concurrent_compactions as well
That way the compactor will get the small L0's out of the lowest level
(too many small sorted runs or global range SSTs (l0) will cause reads to slow down)
b
So is it polling object store? Or is it polling its own local representation? If you have single writer, shouldn't need to poll object store right?
Reading the s3 objects, it seems like we were seeing manifests every 10 seconds, despite no new writes.
c
10s is probably the manifest refresh from the db reader and/or writer
The writer refreshes its manifest every 10s to detect fencing
(that is also tunable with manifest_poll_interval)
b
I see, so if we have our own control plane guarantees on ownership (since its job ID assigned), we could turn that interval to a silly high number?
c
The writer will use its in-memory state for all metadata reads so it shouldn't cause any reads on object storage. The db reader does the same, and re-checkpoints ever so often
Yea, if you know your workload, you can do really abusive stuff that should work quite nicely
e.g. treat l0 like a WAL
b
The reader writes manifests?
c
I originally thought we could do this for everyone, but: https://slatedb.io/docs/faq#why-does-slatedb-have-a-write-ahead-log
The reader writes to the writer's manifest to create and update checkpoints.
(this keeps the compactor from deleting SSTs that the reader might still be using)
b
> By contrast, we don't serve reads from the durable WAL, we only use it for recovery. But DbReader does read the WAL? But this is just to assemble a memtable which the reads are served from?
is there any lazy-fetching or not really?
c
yup, this. After it refreshes its checkpoint, it replays the wal again to re-assemble the writer's immutable memtables that haven't yet been flushed.
meaning have the DbReader start serving reads, and replay the WAL in the background?
b
> meaning have the DbReader start serving reads, and replay the WAL in the background? Yeah I guess my question boils down to is it possible for SlateDB to serve a table that is larger than the available disk on the host? Or does SlateDB always rebuild and keep in fully sync the s3 remote data onto local fs
Hypothetical: if I start up a fresh DbReader to read in one key in SlateDB. What actually ends up getting read from s3?
c
> is it possible for SlateDB to serve a table that is larger than the available disk on the host Absolutely. SlateDB will fall back to reading from S3. You can run SlateDB without any disk at all, in fact. > SlateDB always rebuild and keep in fully sync the s3 remote data onto local fs The replay_wal simply reads the WAL from s3 and writes to in-memory mem-tables. There can be caching, but the caching is not required. > if I start up a fresh DbReader to read in one key in SlateDB. What actually ends up getting read from s3? After the DbReader establishes a checkpoint and replays the WAL (via S3 reads), a get() to a single key will trigger an in-memory SST metadata read. SlateDB keeps SST metadata data in-memory:
Copy code
rust
/// represent the in-memory state of the manifest
#[derive(Clone, PartialEq, Serialize, Debug)]
pub(crate) struct CoreDbState {
    // ...
    pub(crate) l0: VecDeque<SsTableHandle>, // <-- here
    pub(crate) compacted: Vec<SortedRun>,   // <-- and here
    // ...
}
This in-memory lookup determins which SSTs to scan for they key's value baserd on the SST's first/last key. Then it instantiates a bunch of merge iterators for all SSTs in the search set and begins scanning them for the key's value. The merge iterators eventually boil down to SstIterators, which fetch 4kib blocks from 1) it's in-memory cache, 2) the table store. The table store, will in turn attempt to read from the 2.1) object storee cache (4mib object store blocks), then 2.2) s3 itself.
tl;dr a single get follows this flow: 1. in-memory metadata lookups 2. in-memory block cache lookups (4kib each) 3. on-disk object store cache lookups (if set) (4mib each) 4. read from s3 (4mib each)
b
Okay great, that maps a bit better to my mental model. So the s3 reads on startup are basically only for the WAL, everything else is like deferred to some of the data reads. And so when making scans to object store, is it literally making individual 4MiB GET calls? Or is it a configurable
blocks_to_fetch
of blocks for the range (i.e. the 256 default), which means it'll scan
256 * 4KiB
from s3 at a time).
Oh I think I got turned around.. so object store is read in 4MiB size blocks to disk cache, and in-memory blocks are ready in 4KiB size from disk
Really appreciate you answering my questions ๐Ÿ™‚ Okay so I'm a bit new to understanding the internals of an LSM tree. And trying to map it onto the underlying pricing/perf characteristtics of s3. Is there any type of metadata index w.r.t. the keyspace? If we've been compacted up to hypothetically 1GiB L1 file or something.. or even it's still in L0.. and let's say an SST has a key prefix 0000..9999 . If I make a query for the range
[5555*, 8888)
, is there anything that will optimally scan the key range and reduce s3 calls? (EDIT: I think I see this
SsTableIndex
and
BlockMeta
!)
c
(typing to respond ๐Ÿ™‚ )
> So the s3 reads on startup are basically only for the WAL ๐Ÿ’ฏ > is it literally making individual 4MiB GET calls This is a little tricky. The reads that get sent to the table store (thing that wraps s3) are 4KiB block reads. However, if you have the disk cache enabled, those reads get mapped into 4MiB (configurable) reads on S3. If you don't have the disk cache enabled, I believe the reads to S3 are 4KiB. This is a bit fuzzy since the table store will actually coalesce adjacent uncached blocks to reduce S3 calls. So if we're scanning, there are fewer calls to S3. Take a look at https://github.com/slatedb/slatedb/blob/2542e7d3b9b96b0ac403d9ce24d916b7374186a4/slatedb/src/tablestore.rs#L395 to see what the table store does. > so object store is read in 4MiB size blocks to disk cache, and in-memory blocks are ready in 4KiB size from disk Correct, when the disk cache is enabled. When not enabled, IIRC,the S3 reads are 4KiB. > Is there any type of metadata index w.r.t. the keyspace Yup! We keep the index metadata in memory. When you query like your 5555* example, SlateDB scans the in-memory metadata for each SST to see if it fits in that range. If so, it gets included. Take a look at SsTableHandle for all the metadata. And you're right,
SsTableIndex
is tha ctual index. But there's other metadata available as well.
b
Okay great super helpful, so this definitely should have pretty efficient scans on compacted tables for us. Another Q in this peformance realm.. is there a way to 'force compaction'. Since this is basically state storage of a job run, which we also want to support things like 'job replay'. It would be really interesting if we can trigger compaction once the job is complete, so we can trigger compaction for really efficient reads now that we know there's not really more writes planned. Not 100p sure this is ideal, but just kinda in concept sounds nice
c
> is there a way to 'force compaction' Not yet, no. This is something we're discussing a bit at the moment. https://github.com/slatedb/slatedb/issues/673 https://github.com/slatedb/slatedb/issues/288 https://github.com/slatedb/slatedb/issues/166 These are all issues related to the force compaction stuff. It's not directly what you're asking, but if we had something any of these implemented, adding a db.compact() would be easy.
(And yes, your idea is sound. Triggering a compaction would optimize reads after all writes are done. The current
SizeTieredCompactorScheduler
probably won't come up with a schedule that completely compacts things down to one level, but it should improve reads. If you wanted a single fully sorted level, you'd need to probably plug your own compactor scheduler in, which can be done.)
b
got it that makes sense, yeah triggerable compaction would be really nice. I think even without supporting a fully table
db.compact()
, is there anything we can do to trigger the wal->l0 compaction? Or is the only option right now to disable wal, and handle flush ourselves?
That's the most painful thing for us right now, is we can have any number of items in WAL, and since there are no more writes happening for this job it's this forever cost to loading
c
Yea, if you disable compaction, .flush() will force writes to L0. With WAL enabled, there's no good way to do that right now...
> That's the most painful thing for us right now, is we can have any number of items in WAL, and since there are no more writes happening it's this forever cost to loading IIUC, you want a way to manually trigger memtables to L0 so that the replay WAL ID gets bumped, right?
WDYT about something like this:
Copy code
rust
// Flush WAL
db.flush_with_options(FlushOptions::Wal)
// Flush all in-memory memtables up to the max param
db.flush_with_options(FlushOptions::Memtables(1))
// Flush WAL and in-memory memtables (example shows a max of oldest 5 memtables getting flushed)
db.flush_with_options(FlushOptions::WalAndMemtables(5))
b
So new state we're in is: basically is we pulled down the l0 sst size bytes to 1MiB. So now we are advancing the WAL to some extent, so we have some portion of the db that is compacted, and some portion that is still WAL. But then when you load it up, it still has to read the WAL. The scheduled WAL buffering is nice since we don't have to think too hard about durability since we can just await and tolerate the latency. However, reloading db from s3 is slow
yeah I think being able to flush when we're flush the memtables would be great. The model here would be that we still have the data written in the WAL for recovery. But we could manually trigger the db.flush_with_options to write out a compacted table and advance the wal epoch that we recover from?
c
> However, reloading db from s3 is slow I'm very curious about this. If you have a 1MiB L0 max SST size, then that means you should have a max of 1MiB of data in your WAL. So the only way I can think WAL replay would be slow is if you had 1000s of very tiny SSTs (i.e. a lot of very small writes that get flushed to the WAL in very small batches).
How many SSTs do you have between replay WAL ID and the current WAL ID?
correct, yea
b
read manifest (based on the latest manifest ID from list-manifests)
Copy code
[
  7337,
  {
    "external_dbs": [],
    "core": {
      "initialized": true,
      "l0_last_compacted": null,
      "l0": [
        {
          "id": {
            "Compacted": "01K08XR9A3QX8VMARTEW7PR26C"
          },
          "info": {
            "first_key": [
              99,
          ....
            ,
            "end": "Unbounded"
          }
        }
      ],
      "compacted": [],
      "next_wal_sst_id": 361,
      "replay_after_wal_id": 359,
      "last_l0_clock_tick": 1752646296899,
      "last_l0_seq": 358,
      "checkpoints": [
        {
          "id": "ceb86001-cb0a-4251-83be-1c756033b73d",
          "manifest_id": 9,
          "expire_time": {
            "secs_since_epoch": 1752720350,
            "nanos_since_epoch": 0
          },
          "create_time": {
            "secs_since_epoch": 1752646447,
            "nanos_since_epoch": 0
          }
        },
    ...
        {
          "id": "9b1fe4eb-18c5-437c-addd-685a02d50e38",
          "manifest_id": 175,
          "expire_time": {
            "secs_since_epoch": 1752648737,
            "nanos_since_epoch": 0
          },
          "create_time": {
            "secs_since_epoch": 1752648137,
            "nanos_since_epoch": 0
          }
        }
      ],
      "wal_object_store_uri": null
    },
    "writer_epoch": 5,
    "compactor_epoch": 5
  }
]
message.txt is the output from an aws s3 ls on the wal prefix on s3
c
"next_wal_sst_id": 361, 2025-07-15 23:29:41 74 00000000000000000445.sst
b
WAL goes as far as 445.sst
c
Ya
So 84 SST reads...
๐Ÿค”
b
so that's like ~80 WAL files that must be read for each startup right?
c
How long does startup take for you?
Yes, though they can be fetched in parallel. Lemme check the code
Copy code
let sst_iter_options = SstIteratorOptions {
    max_fetch_tasks: 1,
    blocks_to_fetch: 256,
    cache_blocks: false,
    eager_spawn: true,
};

let replay_options = WalReplayOptions {
    sst_batch_size: 4,
    min_memtable_bytes: self.settings.l0_sst_size_bytes,
    max_memtable_bytes: usize::MAX,
    sst_iter_options,
};
Looks like we do 4 SSTs in parallel
b
yeah it's also a lot of API calls, since imagine that this is a state store per run, and at least when the job was running we presumably had a memtable ready to be flushed. if we had the API that you mentioned above of
flush_with_options
to be able to manually trigger the flush on job completion, that probably is killer
c
Yea I'd love to know how long that 80-SST wal replay takes for you
b
not super representative, but I can test from my laptop to s3 fairly easily
c
Yea.. that's going to be wildly inaccurate since you're traversing the open internet.
b
yup..
c
If we assume 4 SSTs in parallel, and each SST fetch takes network latency of 10ms, we'd hvae 80 / 4 = 20 sequential fetches = 200ms
If you haven't run it in a cloud provider in the same AZ/region as your bucket (ideally with VPC gateway), you're probably not getting a very useful measurement.
b
Oh we've been testing this in prod in shadow. We were seeing latencies of like 10s+ to do a "getall" of I think ~100MB
And the usage pattern was basically sidecar writer which the job uses + a shared web server reader for the UI to read. Web server did the following: 1. lazily created a slatedb instance upon web request, save in a cache 2. then serve the read request as a
scan
After moving off of the sidecar approach and separate reader and just having a shared writer server that all jobs write to, our 'read after write' latency for a live run is far better, but I don't have a rigorous measurement for you rn. Can try to get you something soon
c
Hmmm . โ€œGet allโ€ = WAL replay? Or scan(..)?
b
sorry, yeah a scan
c
10s to do a scan of 100mib would indicate the lower levels have a lot of (small) SSTs in themโ€ฆ Also, are you using disk cache?
b
Okay I have some real numbers now. Manifest is attached, max wal is 1436. replay_after_wal_id: 1164 The attached graph is measuring the load time have a slatedb writer instance
This is measured from a container running in us-west-2, accessing a bucket in us-west-2. I'm not 100p confident that my VPC endpoint is working as intended, but should be fair-ish numbers
Each instantiation is fetching with a new object store cache path (and amazon s3 builder). Unfortunately it does include some overhead of getting sts creds
c
Y axis is seconds?
b
yup
c
K.. Iโ€™ll poke at this a bit tomorrow AM ๐Ÿ™‚
b
thanks so much!! would it be helpful if I gave you the WAL data sizes?
c
Ya that would be really helpful. Ideally at the per-SST granularity
b
c
Thx!
b
no -- thank you!!
c
No prob.. ๐Ÿ™‚ SlateDB must be fast! ๐Ÿ˜€
I have a suspicion itโ€™s some configs that need to be tweaked.. will try and figure out whatโ€™s up
b
Yup makes sense, I was playing around with a local fork and turning up the max_fetch_tasks and sst_batch_size definitely helped just from some local testing
c
haha yea that would make sense
b
> Also, are you using disk cache? Disk cache is the object store cache or something else? Is it content-addressed or something so it's safe to use across multiple SlateDBs on the same host? Or it's bucket path?
c
> Disk cache is the object store cache or something else Ya, sorry, same thing--object store cache
> Is it content-addressed or something so it's safe to use across multiple SlateDBs on the same host? Or it's bucket path? Oh, that's a good question (cc @flaneur233). I'm not sure if it can be shared safely between processes on the same host. I know the block cache can. But IIRC, the object store cache has some background processes that might fight with each other if multiple processes point to the same dir.
Interesting.. so yea, this is definitely a somewhat pathological case in that it's low throughput.. which results in a lot of small WALs.. and memtables don't get flushed very often
272 WAL entries for replay_after_wal_id with a total size of only 617KiB
So yea.. we'd either have to bump up the replay wal SST parallelism a lot or give you a
flush_with_opts
so you can flush the memtables every so often. I'm going to open a GH issue for this. It should be a pretty straightforward fix
With 272 WAL entries, if it takes ~3s to replay, then it's replaying about 90 WAL entries per second. Comes out to ~11ms per fetch if it were sequential (which it isn't). Not totally crazy. I think S3 latency is around there (https://github.com/dvassallo/s3-benchmark).
In any case, let's GH issue it and we can work through a fix.
b
In our case it's actually one shared process (tonic grpc server) which is holding many Db structs in a Cache. Right now we just make a random cache dir for each Db
> Interesting.. so yea, this is definitely a somewhat pathological case in that it's low throughput.. which results in a lot of small WALs.. and memtables don't get flushed very often Yeah this was what I was worried about.. thanks for helping out debugging with this! Will look out for the Github Issue ๐Ÿ™‚
f
i think having multiple slatedb instances in a same host is mostly same as running multiple slatedb instances across machines, and yes, the local disk cache can be shared to improve the cache utilization i think ๐Ÿค”. users have to take care about only enabling the evictor in a single process, or they'd likely to fight with each other.
c
@brainhart.dev Got a GH account username? I'm opening the issue now.
Also, I'm curious, if you bump
sst_batch_size
in db::replay_wal` way up (like.. 1024), what does startup time look like?
I'm also curious if you simply disable WAL and handle your own flushes if that fixes things for you
b
brainhart
> Also, I'm curious, if you bump sst_batch_size in db::replay_wal` way up (like.. 1024), what does startup time look like? will test later! I know we saw improvement locally, but would want to test in a real environment!
> I'm also curious if you simply disable WAL and handle your own flushes if that fixes things for you this would probably be harder for us to test, since it would require us to change our underlying usage pattern a bit. One of the reasons I like the
flush_with_opts
approach would be if we can basically maintain the WAL, but then trigger a memtable flush on job completion. But being able to
db.compact()
would be preferred ofc, just that
flush_with_opts
might be 'close enough' for us
c
๐Ÿ‘‹ @brainhart.dev just checking in. I'm working on the memtable flush API right now. Are things working OK for you?
b
Yeah things are working alright now that we've switched architecture patterns away from sidecar
c
Great. flush_with_options has been merged and will be available in 0.8. This will let you flush memtables manually.