You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
HSCAN/SSCAN/ZSCAN over a large collection are 10-20x slower than Redis (O(N^2/1024) full iteration) #770
Found while fixing #751 (#769). A full iteration of HSCAN / SSCAN / ZSCAN over a 200,000-element collection is 10-20x slower than Redis 8.10.2 (D4s_v5, redis-py):
KiviDB
Redis
HSCAN 200k
380 ms
32 ms
SSCAN 200k
718 ms
33 ms
ZSCAN 200k
668 ms
40 ms
They use the same "hash every element on every call" scan_page that SCAN used before #769, with a len/1024 page floor, so a full iteration costs O(N^2/1024). The matcher isn't the cost.
Unlike the keyspace (where #769 reuses the 12-bit hash fragment the shard table already stores per slot), these collections keep no per-element hash fragment, so the fix needs a design choice: store a scan position per element, use a structure ordered by position, or reuse the collection's own table slot fragment if its hash table already has one. Must keep the SCAN guarantee (every element present for the whole iteration is returned at least once) across growth and shrink, and must not add memory per element without measuring it.
@magic-peach yes, it's yours! The issue has the design question: these collections keep no per-element hash fragment like the keyspace table does (#769 used the slot's 12-bit fragment as the scan position). Before coding, please comment here with your approach (e.g. reuse the collection's own hash table slot hash if it has one, or store a position per element) and its memory cost per element, so we agree on it first. The SCAN guarantee must hold (every element present for the whole iteration is returned at least once, across growth and shrink).
My plan is to store each element's scan position next to it, instead of hashing every element on every call.
Every HSCAN, SSCAN or ZSCAN call hashes the whole collection to find one page. It also copies about half the elements into a Vec and runs select_nth on it. So a full iteration costs calls × N.
Why I'm not reusing the collection's own hash table:
Sets: the set is a hashbrown HashTable, which keeps only 7 bits of each element's hash. Elements can sit away from their home bucket and get moved when the table grows, so a cursor based on bucket index would break the SCAN guarantee.
Hashes: IndexMap stores a full hash per entry, but it isn't part of its public API. Its order also changes when HDEL calls swap_remove.
The approach:
When an element is inserted, compute scan_position once with the same fixed seed used today and store it beside the element.
Set: HashTable<(Arc<[u8]>, u64)>
Hash: the field value becomes (Arc<[u8]>, u64)
Sorted set: the members value becomes (f64, u64)
The position depends only on the element's bytes, not on the table. Growing, shrinking and rehashing never change it, so the SCAN guarantee holds exactly as it does now. It is also the same after AOF/RDB load and on replicas, so it doesn't need to be saved.
scan_page then works the way perf(scan): find SCAN pages from the slots' hash fragments #769 does:
a. A first pass reads only the stored positions. It counts elements per 4096 buckets (the top 12 bits) and picks enough buckets to cover want.
b. A second pass visits only the elements in those buckets.
There's no hashing, no Vec of the whole collection and no select_nth, and a position is never split across two pages.
Memory: about +8 bytes per element. A u16 or u32 position costs the same because of alignment padding (the slot grows from 16 to 24 bytes for sets, and the value grows by 8 bytes for hashes and sorted sets), so I'd store the full u64.
Does this sound right before I start?
Thanks @magic-peach for writing the plan down before starting; that saved both of us a round. The analysis of why the current tables can't give a cursor is right (hashbrown keeps 7 bits and moves elements when it grows; IndexMap's order changes on swap_remove). Two things stop me from saying go on this shape, though:
It is still a pass over the whole collection per call. Step (a) reads every stored position to count per bucket, so a full iteration stays calls × N. It gets much cheaper per element (no hashing, no Vec, no select_nth), but a 3M-field hash scanned in pages of 10 is still 300,000 passes over 3M positions. Redis's cost per call is the page.
What gets both right is a cursor that comes from the table's own layout, with nothing stored per element: the way the keyspace's own SCAN works here (src/store/shard_map.rs: its buckets are reached by index, and the cursor survives the table growing). Collections don't sit in a table like that today, and how they are stored is being decided right now for the memory issues above. If large collections move onto that kind of table, HSCAN/SSCAN/ZSCAN get a real cursor from it, and anything built on the current tables in the meantime would be thrown away.
So my suggestion is to hold the structural fix until that is settled (days, not months; I'll write the outcome here), rather than have you build something we then replace. Two things you could do now if you want to keep going in this area:
A cheaper pass with no stored state, if you see one: for instance step (b) without step (a)'s memory, by hashing only (still O(N) hashing per call, but no copy and no select_nth). Only worth it if it is small and clearly faster; numbers first.
Also for the record: #624 is the same problem from the top-level side and is assigned to @Parikalp-Bhardwaj, so whatever lands here has to be one design for both.
@murtazayusuf while the storage decision is pending, is it fine if I try the cheaper pass you suggested?
The idea is to keep hashing each element on every call, but find the page in two passes like #769, with nothing stored per element:
Hash every element and count how many fall in each of 4096 position buckets, starting from the cursor. Then pick buckets until the page is full.
Hash again and return only the elements in those buckets.
This removes the Vec copy of the collection and the select_nth, and a bucket is never split across two pages, so the SCAN guarantee holds as it does now. Each call still costs O(N) hashing, so it's only a stopgap until the table-based cursor lands.
@magic-peach yes, go ahead with that as the stopgap, on these terms so it is worth merging: numbers first and in the PR (a full iteration of a 1M-member set, hash and sorted set at COUNT 10, 100 and 1000, master against your branch against Redis; plus one call on a 10-element collection, which must not get slower: hashing everything twice has to beat one hash plus the copy even when N is tiny, or small collections need to keep today's path); the guarantee tested as today's tests do it (every element present for the whole scan is returned, under inserts and deletes between calls,
8000
across a rehash); nothing stored per element and no change to the collections' types; and the cursor format unchanged, so a client holding a cursor across an upgrade keeps iterating correctly (say in the PR if that can't hold). Regression suite rows go under benchmarks/1.3.0/regressions/suites/ as usual. If the gain turns out small (well under 2x on the full iteration), say so and we skip it rather than carry the code until the real cursor lands. After #866, please.
It hashes each member once per call, counts members per range of positions, and keeps only the ranges the page can take. There's no copy and no select_nth, nothing is stored per member, and the cursor format is unchanged. Full iteration over 1M members, release builds on my Mac, median of 3:
Hashes get 2×, but sets only ~1.25× and sorted sets ~1.35×. Most of the cost is reading every member to hash it, not the copy. Hashes are walked in insertion order, so their copy was a bigger share. A first call on a 10- or 200-member collection is unchanged.
@magic-peach thank you for measuring before opening anything; that is exactly the answer needed. Let's skip it: 1.25x and 1.35x for sets and sorted sets is not worth carrying code that the table-based cursor replaces, and taking it for hashes alone would leave the three commands behaving differently for a 2x that is still a pass over the whole collection per call. The useful result is the one you found on the way: most of the cost is reading every member to hash it, not the copy, so nothing short of a cursor that comes from the table will fix this. I'll note that in the storage decision, and this issue stays yours for the real fix once that is settled. If you'd like to push the branch somewhere so the numbers can be reproduced later, link it here. Meanwhile the suite script for mastodon-feed-fanout in #849 is open if you want it.
@murtazayusuf since #907 and #624 closing into this, #770 is now just the per-page read of large collections. Has the storage decision for large sets and hashes been made? Once it is, I can build the cursor from the table, as shard_map.rs does for the keyspace. For ZSCAN I'd fit it to the counted tree from #875, so there's one design for all three.
@magic-peach not yet: the small forms are all in (#872 sets, #886 hashes, #895 lists, #926 sorted sets), the large hash/set table is the piece still open, and it is next on my side. I'll post the design on #764 and link it here; you won't have to guess at it.
What is already fixed, whatever the layout turns out to be: the cursor comes from the table itself, a reverse-binary cursor over a power-of-two bucket array as shard_map.rs does for the keyspace, so a page costs its own buckets and survives a resize with Redis's guarantees (every element present for the whole scan is returned at least once). The table will expose exactly that walk (scan(cursor, count, |entry|) -> next), and HSCAN/SSCAN become thin callers. So this stays yours, and it can start as soon as the design is up.
Agreed on ZSCAN: one design, fitted to the counted tree from #875 (a cursor that is a rank or a member position there, not a bucket), so it waits
8BD0
for @Parikalp-Bhardwaj's layout.
@magic-peach status: the table's second piece is merged (#964: entries in their own slab pool, a cheaper random pick, the API sets and hashes need; scan's signature is unchanged and your table_scan tests pass on it). Large sets are moving onto the table now, and that PR wires SSCAN through your sscan_reply and measures a full iteration through the server against master and Redis; it carries your credit. Hashes follow, and HSCAN with them (the hide-due-fields test will come from the caller until TTLs move into the entries). Nothing needed from you for the sets step; I'll point you at the PR when it is up in case you want to look at how your builder is called.
@magic-peach#965 is merged: large sets are on the new table and SSCAN goes through table_scan::sscan_reply, your builder, credited in the CHANGELOG. A full SSCAN of a 1M-member set at COUNT 100 went from 33 s to 2.2 s, level with Redis 8.10.2. HSCAN comes with the hash step, which starts now; ZSCAN after that.
@murtazayusuf thanks for wiring SSCAN through sscan_reply, and for carrying the hash step in #976. For ZSCAN, could I take it once #875's layout is on master? I'd write it the same way: a zscan_reply page builder in table_scan.rs over the sorted set's table, wired in when large sorted sets move over. If you'd rather fold it into that step yourself, that's fine too. Once #976 merges, I can also add the test from your #955 review that counts pages taken while a resize is still unfinished.
@magic-peach yes: ZSCAN is yours once the sorted-set layout from #875 is on master. Until then there is nothing stable to put a cursor on, so please don't start on today's structure. I'll say here when it lands. In the meantime #975 is the one to finish (the review is on the PR).
#976 is merged: HSCAN over a large hash now goes through the table's cursor (1M fields: about 0.36-2.4 s of server CPU for a full scan depending on COUNT, level with Redis), as SSCAN does since #965. ZSCAN is what is left here, after #875.
Closed by #989. @magic-peach, I had said ZSCAN would be yours once the sorted-set layout was on master; in the end the cursor fell out of the layout change itself (the table that holds the members is the one SSCAN and HSCAN already page through), so #989 carries it, on the page builder you wrote in #955, and the CHANGELOG entry credits you for it. If you want something of your own in this area, the two follow-ups from #975 are still yours.
Activity
magic-peach commentedon Nov 14, 2026
@murtazayusuf can I work on this?
murtazayusuf commentedon Nov 14, 2026
@magic-peach yes, it's yours! The issue has the design question: these collections keep no per-element hash fragment like the keyspace table does (#769 used the slot's 12-bit fragment as the scan position). Before coding, please comment here with your approach (e.g. reuse the collection's own hash table slot hash if it has one, or store a position per element) and its memory cost per element, so we agree on it first. The SCAN guarantee must hold (every element present for the whole iteration is returned at least once, across growth and shrink).
bench(regressions): fail loudly on broken, partial or unrecordable runs
magic-peach commentedon Nov 17, 2026
My plan is to store each element's scan position next to it, instead of hashing every element on every call.
Every HSCAN, SSCAN or ZSCAN call hashes the whole collection to find one page. It also copies about half the elements into a Vec and runs select_nth on it. So a full iteration costs calls × N.
Why I'm not reusing the collection's own hash table:
The approach:
When an element is inserted, compute scan_position once with the same fixed seed used today and store it beside the element.
The position depends only on the element's bytes, not on the table. Growing, shrinking and rehashing never change it, so the SCAN guarantee holds exactly as it does now. It is also the same after AOF/RDB load and on replicas, so it doesn't need to be saved.
scan_page then works the way perf(scan): find SCAN pages from the slots' hash fragments #769 does:
a. A first pass reads only the stored positions. It counts elements per 4096 buckets (the top 12 bits) and picks enough buckets to cover want.
b. A second pass visits only the elements in those buckets.
There's no hashing, no Vec of the whole collection and no select_nth, and a position is never split across two pages.
Memory: about +8 bytes per element. A u16 or u32 position costs the same because of alignment padding (the slot grows from 16 to 24 bytes for sets, and the value grows by 8 bytes for hashes and sorted sets), so I'd store the full u64.
Does this sound right before I start?
murtazayusuf commentedon Nov 17, 2026
Thanks @magic-peach for writing the plan down before starting; that saved both of us a round. The analysis of why the current tables can't give a cursor is right (hashbrown keeps 7 bits and moves elements when it grows;
IndexMap's order changes onswap_remove). Two things stop me from saying go on this shape, though:*SCAN. Collections are where we are furthest behind Redis per element today (Memory: a big hash uses ~2.7x Redis's memory per field (3M fields: 296 MiB vs 109 MiB) #764, Sorted sets (800 members): 53% more memory than Redis, and BGSAVE peak grows ~0.46 GiB under writes (Mastodon home feeds) #825, Small collections use significantly more memory than Redis compact encodings #297 are all that), and that number has to go down, not up. A set member is 16 bytes of slot now; 24 is +50% of the table.Vec, noselect_nth), but a 3M-field hash scanned in pages of 10 is still 300,000 passes over 3M positions. Redis's cost per call is the page.What gets both right is a cursor that comes from the table's own layout, with nothing stored per element: the way the keyspace's own
SCANworks here (src/store/shard_map.rs: its buckets are reached by index, and the cursor survives the table growing). Collections don't sit in a table like that today, and how they are stored is being decided right now for the memory issues above. If large collections move onto that kind of table,HSCAN/SSCAN/ZSCANget a real cursor from it, and anything built on the current tables in the meantime would be thrown away.So my suggestion is to hold the structural fix until that is settled (days, not months; I'll write the outcome here), rather than have you build something we then replace. Two things you could do now if you want to keep going in this area:
select_nth). Only worth it if it is small and clearly faster; numbers first.EXEC): you already know that code from ASKING before MULTI covers the transaction up to its EXEC #746, the two failing cases are written up there, and it is a correctness bug rather than a speed one.Also for the record: #624 is the same problem from the top-level side and is assigned to @Parikalp-Bhardwaj, so whatever lands here has to be one design for both.
magic-peach commentedon Nov 17, 2026
@murtazayusuf while the storage decision is pending, is it fine if I try the cheaper pass you suggested?
The idea is to keep hashing each element on every call, but find the page in two passes like #769, with nothing stored per element:
This removes the Vec copy of the collection and the select_nth, and a bucket is never split across two pages, so the SCAN guarantee holds as it does now. Each call still costs O(N) hashing, so it's only a stopgap until the table-based cursor lands.
murtazayusuf commentedon Nov 17, 2026
@magic-peach yes, go ahead with that as the stopgap, on these terms so it is worth merging: numbers first and in the PR (a full iteration of a 1M-member set, hash and sorted set at
COUNT 10,100and1000, master against your branch against Redis; plus one call on a 10-element collection, which must not get slower: hashing everything twice has to beat one hash plus the copy even when N is tiny, or small collections need to keep today's path); the guarantee tested as today's tests do it (every element present for the whole scan is returned, under inserts and deletes between calls, 8000 across a rehash); nothing stored per element and no change to the collections' types; and the cursor format unchanged, so a client holding a cursor across an upgrade keeps iterating correctly (say in the PR if that can't hold). Regression suite rows go underbenchmarks/1.3.0/regressions/suites/as usual. If the gain turns out small (well under 2x on the full iteration), say so and we skip it rather than carry the code until the real cursor lands. After #866, please.magic-peach commentedon Nov 17, 2026
@murtazayusuf I built the stopgap and measured it.
It hashes each member once per call, counts members per range of positions, and keeps only the ranges the page can take. There's no copy and no select_nth, nothing is stored per member, and the cursor format is unchanged. Full iteration over 1M members, release builds on my Mac, median of 3:
Hashes get 2×, but sets only ~1.25× and sorted sets ~1.35×. Most of the cost is reading every member to hash it, not the copy. Hashes are walked in insertion order, so their copy was a bigger share. A first call on a 10- or 200-member collection is unchanged.
Do let me know if its fine or I should skip it
murtazayusuf commentedon Nov 17, 2026
@magic-peach thank you for measuring before opening anything; that is exactly the answer needed. Let's skip it: 1.25x and 1.35x for sets and sorted sets is not worth carrying code that the table-based cursor replaces, and taking it for hashes alone would leave the three commands behaving differently for a 2x that is still a pass over the whole collection per call. The useful result is the one you found on the way: most of the cost is reading every member to hash it, not the copy, so nothing short of a cursor that comes from the table will fix this. I'll note that in the storage decision, and this issue stays yours for the real fix once that is settled. If you'd like to push the branch somewhere so the numbers can be reproduced later, link it here. Meanwhile the suite script for
mastodon-feed-fanoutin #849 is open if you want it.magic-peach commentedon Nov 17, 2026
@murtazayusuf I'll take mastodon-feed-fanout.
magic-peach commentedon Nov 19, 2026
@murtazayusuf since #907 and #624 closing into this, #770 is now just the per-page read of large collections. Has the storage decision for large sets and hashes been made? Once it is, I can build the cursor from the table, as shard_map.rs does for the keyspace. For ZSCAN I'd fit it to the counted tree from #875, so there's one design for all three.
murtazayusuf commentedon Nov 19, 2026
@magic-peach not yet: the small forms are all in (#872 sets, #886 hashes, #895 lists, #926 sorted sets), the large hash/set table is the piece still open, and it is next on my side. I'll post the design on #764 and link it here; you won't have to guess at it.
What is already fixed, whatever the layout turns out to be: the cursor comes from the table itself, a reverse-binary cursor over a power-of-two bucket array as
shard_map.rsdoes for the keyspace, so a page costs its own buckets and survives a resize with Redis's guarantees (every element present for the whole scan is returned at least once). The table will expose exactly that walk (scan(cursor, count, |entry|) -> next), and HSCAN/SSCAN become thin callers. So this stays yours, and it can start as soon as the design is up.Agreed on ZSCAN: one design, fitted to the counted tree from #875 (a cursor that is a rank or a member position there, not a bucket), so it waits 8BD0 for @Parikalp-Bhardwaj's layout.
4 remaining items
HSCAN and SSCAN pages over CollectionTable::scan (#770)
Merge pull request #955 from magic-peach/feat/table-scan-cursor
murtazayusuf commentedon Nov 19, 2026
@magic-peach status: the table's second piece is merged (#964: entries in their own slab pool, a cheaper random pick, the API sets and hashes need;
scan's signature is unchanged and yourtable_scantests pass on it). Large sets are moving onto the table now, and that PR wiresSSCANthrough yoursscan_replyand measures a full iteration through the server against master and Redis; it carries your credit. Hashes follow, andHSCANwith them (the hide-due-fields test will come from the caller until TTLs move into the entries). Nothing needed from you for the sets step; I'll point you at the PR when it is up in case you want to look at how your builder is called.Merge pull request #965 from kividbio/feat/sets-on-the-table
murtazayusuf commentedon Nov 20, 2026
@magic-peach #965 is merged: large sets are on the new table and
SSCANgoes throughtable_scan::sscan_reply, your builder, credited in the CHANGELOG. A full SSCAN of a 1M-member set at COUNT 100 went from 33 s to 2.2 s, level with Redis 8.10.2. HSCAN comes with the hash step, which starts now; ZSCAN after that.magic-peach commentedon Nov 20, 2026
@murtazayusuf thanks for wiring SSCAN through
sscan_reply, and for carrying the hash step in #976. For ZSCAN, could I take it once #875's layout is on master? I'd write it the same way: azscan_replypage builder intable_scan.rsover the sorted set's table, wired in when large sorted sets move over. If you'd rather fold it into that step yourself, that's fine too. Once #976 merges, I can also add the test from your #955 review that counts pages taken while a resize is still unfinished.murtazayusuf commentedon Nov 20, 2026
@magic-peach yes: ZSCAN is yours once the sorted-set layout from #875 is on master. Until then there is nothing stable to put a cursor on, so please don't start on today's structure. I'll say here when it lands. In the meantime #975 is the one to finish (the review is on the PR).
Merge pull request #976 from kividbio/feat/hashes-on-the-table
Large hashes on CollectionTable (kividbio#764 step 3), HSCAN through …
murtazayusuf commentedon Nov 20, 2026
#976 is merged:
HSCANover a large hash now goes through the table's cursor (1M fields: about 0.36-2.4 s of server CPU for a full scan depending onCOUNT, level with Redis), asSSCANdoes since #965.ZSCANis what is left here, after #875.Large sets on CollectionTable (kividbio#764 step 2), SSCAN through it…
Merge pull request #989 from kividbio/feat/zsets-on-the-table
murtazayusuf commentedon Nov 20, 2026
Closed by #989. @magic-peach, I had said ZSCAN would be yours once the sorted-set layout was on master; in the end the cursor fell out of the layout change itself (the table that holds the members is the one
SSCANandHSCANalready page through), so #989 carries it, on the page builder you wrote in #955, and the CHANGELOG entry credits you for it. If you want something of your own in this area, the two follow-ups from #975 are still yours.Large sorted sets on CollectionTable, ZSCAN through its cursor