12 ms·
35% Faster Than The Filesystem (2017)
- toxik 7y agoWhile an impressive feat on SQLite’s end, I sincerely hope no engineers see this and take it at face value. The filesystem is slower because it is more flexible, and I would imagine that once you have concurrent reads and writes to your thumbnails, a filesystem is to prefer.
- chias 7y agoIMO the point of this article is pretty clearly to answer the developer question "my application needs to read and write data, should I use the filesystem or should I use a sqlite db?" and not make some kind of sweeping "sqlite > fs" claim. In this context, face value is fine.
- zzzcpan 7y agoTheoretically there could exist filesystems that can do well on thumbnails and small files, but in practice this has never been true. Databases are typically better at this and specialized solutions can get you even farther, like over an order of magnitude barrier farther.
- wtallis 7y agoIf you want to support concurrent reads and writes, you probably should pick a particular database engine and understand its concurrency semantics, instead of assuming that whatever filesystem your software lands on will have the semantics you expect.
- blinkingled 7y ago> The performance difference arises (we believe) because when working from an SQLite database, the open() and close() system calls are invoked only once, whereas open() and close() are invoked once for each blob when using blobs stored in individual files. It appears that the overhead of calling open() and close() is greater than the overhead of using the database. The size reduction arises from the fact that individual files are padded out to the next multiple of the filesystem block size, whereas the blobs are packed more tightly into an SQLite database. open() and close() are significantly slower[1] on non-Linux OSes so this would be even more drastic on say Windows or macOS. [1] I once had to debug a library that was lot slower on Mac and Windows and it mostly turned out to be because of doing open/close of files instead of caching the handles - on Linux it was barely showing up on the perf traces and I had no easy way to debug on the other OSes. On a hunch I cached the file handles and the performance difference was mostly gone.
- vdfs 7y agoAlso doesn't make any sense, of course something that use open/close once will be faster than using open/close n time.
- blinkingled 7y agoIt gets weird when you throw Linux in the mix - open/close are extremely cheap on Linux, to the point of being free - at least used to be before Spectre and Meltdown and what not. So on Linux doing n more open/closes isn't much different than doing a single pair if n is not humongous and the program is doing other things besides just open close.
- zaroth 7y agoFor small- to mid-sized projects, I’ve always realized huge gains in simplicity by haves “Files” tables to store various assets. It means instances in a web-farm can pull the files down when they initialize easily, it means files are automatically versioned, it provides an obvious place to put the files when they are being uploaded on the Admin panel. It means all the files are getting backed up as part of the database snapshots automatically. Things I’ve used this for range from static HTML assets, to logos which are used to dynamically brand a page, to files that get attached to transactional emails, etc. So yes, if you are building a massive scale system holding millions of files, sure, find a purpose-built system to store, distribute, version, and backup your files. But for many projects I believe the files-in-database approach is dismissed too early for not being “clean” enough. But having a single source (the DB) for everything the app needs to initialize is a massive simplification. You may find it’s well worth the trade-offs. Really the only downside I ever found — at the scale I was operating at — was that it bloats the database backups.
- messe 7y ago> was that it bloats the database backups. Having a deduplicating backup solution might help with that. Simplest way to do that (in terms of ease-of-implementation), would be to keep backups on a ZFS or btrfs filesystem. Note that (AFAIK) with btrfs, deduplication must be triggered manually, so you'd need to run `btrfs filesystem defragment` on the backups to take advantage of it.
- Filligree 7y agoNote for other readers: The parent post probably means incremental ZFS snapshots, which won't store multiple copies of any given block unless the piece of data has been moved. ZFS also has a block deduplication scheme, but turning it on is a poor idea. The deduplication table needs to be stored in memory for decent performance, and this takes a lot of memory. Even then, performance is rarely as good as with dedup turned off. It doesn't even save as much space as you'd hope -- it's per-record, and ZFS storage records are 128KiB by default. If you're trying to deduplicate 10KiB files with that, you're going to have a bad time. (Note also: The ZFS record size is dynamic; the 128KiB default is the maximum record size it'll allow, i.e. the most data that has to be read and rewritten (somewhere else) if you modify one byte in a larger file. If you just write a single 10KiB file and force it to disk, then you'll get a 10KiB record. It's complicated; try not to read more into this than "dedup is rarely a good idea," though if I'm allowed a second line, I'll add "compression is always a good idea; enable zle at a minimum.")
- pedrocr 7y agoIn the past I've had huge speedups by moving simple single-table databases that had grown a bit (e.g., time series data) from sqlite to postgres. Insert performance is also quite bad forcing you to write applications with extra caching layers to be able to do a bunch of inserts at once. Sqlite is great for many applications but it's speed is somewhat oversold. I really wish the postgres engine was embeddable into applications easily.
- hizanberg 7y agoObviously if it was embeddable it wouldn’t be as fast and be subject to the same design limitations as SQLite.
- pedrocr 7y agoThere's nothing about being embeddable that's a limitation. All I really want is a lib I can link to that gives me an entry point to launch the database against a given folder, with some of the tweaks the postgres config file has, and that gives me a connection back. That entry point can launch however many threads it wants and behave exactly like postgres itself. After that my app can connect to a standard postgres and take advantage of all the features and performance. We've been moving so much into web apps that optimizing for desktop apps like these is not a big concern these days. Sqlite ends up being used in that niche but it's extremely easy to run into it's limitations even in very simple personal usage. It's fine for what it is, an alternative to open(), but there are plenty of use cases where optimizing for fast open is not relevant. Here's an example of where I'd really like postgres to replace sqlite: https://github.com/pedrocr/syncer/ https://github.com/pedrocr/syncer/ I've had to add an extra caching layer because of sqlite INSERT performance. Given that I've already had to code around limitations and the schema is simple I will probably end up using a simpler non-SQL database in the future instead.
- hizanberg 7y ago> There's nothing about being embeddable that's a limitation. An always-running in-memory server process is going to be a lot better at concurrency than multiple embeddable libraries trying to take locks out on the same file on disk.
- Tepix 7y agoWhat if you create something that is optimized for performance without offering the full SQL language? Just a container to store small files with padding to avoid the expensive open/close calls.
- hizanberg 7y agoLook at Google’s LevelDB and Facebook’s RocksDB.
- pjc50 7y agoRead-only versions of this are extremely common for games; I first encountered it with 90s DOOM WAD files.
- typon 7y agoWrite API abstractions that offer baked and templated Sql queries for your specific use case. Flexible enough for future growth, easy enough for every day normal use without inventing a whole new system.
- iforgotpassword 7y agoMinecraft vastly improved performance when it switched from having one file per 16x16 map area to just stuffing 32x32 of those chunks into one file with a simple index at the beginning.
- liability 7y agoI'm not sure how much better you'd get than sqlite if you were using a straight forward rowid select with a prepared statement. Sqlite is pretty damn snappy for something like that and using a prepared statement amortizes the cost of compiling the SQL.
- zzzcpan 7y agoYou can get a point read with just a single aligned random I/O operation on disk with this. I don't see how a B-tree based storage can compete. And even more optimizations are possible, like grouping objects often accessed together into a single batch to retrieve the whole group in just one random operation too.
- cfstras 7y agoThis might be the answer on how to make file-heavy tools like npm/yarn work adequately on windows...
- OJFord 7y agoNext week on Show HN: `sqlitefs`, the SQLite-backed FUSE filesystem?
- progval 7y agoHaving it on top of FUSE would make it significantly slower than an in-kernel filesystem.
- mirekrusin 7y agoIt would be interesting to see how it performs ie. on nodejs projects with node_modules.sqlite3 - for practical reasons it would be nice to mount it via fuse to node_modules - if needed.
- dana321 7y agoWell, to be fair, it would be a lot faster than mysqlfs.
- ruuda 7y agoSomething similar exists: https://www.youtube.com/watch?v=wN6IwNriwHc https://www.youtube.com/watch?v=wN6IwNriwHc
- ngirard 7y agoInteresting project, thanks. For the record, their GitHub repository is https://github.com/samzyy/DB-based-replicated-filesystem https://github.com/samzyy/DB-based-replicated-filesystem
- dymk 7y agohttps://github.com/guardianproject/libsqlfs https://github.com/guardianproject/libsqlfs already exists
- devnonymous 7y agoI've taken a stab at this and made quite a bit of progress. However, the idea was to use the sqlite fuse layer as a stacked layer over the underlying filesystem rather than a full scale file-system (which for example, is what libsqlfs provides). The motivation was not to improve filesystem performance but improving the speed of querying (ie: lightning fast stat of the entire deeply nested directory tree) at the expense of slower writes. Additionally I could (in theory, never got around to it) store rich metadata about the files, build all sorts of indexes, apply a richer access-control mechanism etc. Unfortunately, it remains in pre-alpha state, because life.
- dTal 7y agoThis shouldn't be especially surprising - in fact I would expect this to be the case, all other things being equal, for two reasons: firstly, open() followed by read() involves two kernel-userspace context switches, while SQLite operating on an already open file only needs to call read(), and secondly SQLite is more aggressive about making forwards-incompatible changes than most popular filesystems, giving it more latitude to optimize (ZFS is an exception, but with most filesystems you expect a 10-year old computer to read a disk created yesterday).
- notyourday 7y agoAs someone who has spent time consulting for different kinds of "we do stuff on the internet" companies, I can confidently say that this is a premature optimization for 99.999% of the companies/projects. The companies simply don't have enough IO traffic to need it. Is it cool? Sure. Is it sexy? Maybe. Is it needed? Nope. Do boring stuff. Use files. If you send your small files over the internet via web and you need to squeeze additional performance, do boring stuff again: use Varnish.
- dana321 7y agoFirst thing you can do is just add more RAM, any free ram will be used to cache disk access. Varnish will decrease the latency only if you are using some scripting between the file and its access.
- notyourday 7y agoIf you are at the point where you need to handle more IO, throwing additional memory onto a file origin will not in my experience do much because filesystems's idea of what to cache is vastly different from user's requests. Not doing any disk IO for hot files is vastly preferable than to doing some. This has been demonstrated in spades at LiveJournal which extensively stuffed files into memcache before Varnish became a thing.
- fvdessen 7y ago> Do boring stuff. Use files. I have the opposite experience. Files are far from 'boring', they have too many gotchas to count. Putting files in the db is for many use-cases actually easier than putting them on the filesystem. By putting all data in the db you have less moving parts, transactions, referential integrity, well defined behaviours, etc. The speed increase is just a nice side effect.
- notyourday 7y ago> By putting all data in the db you have less moving parts, transactions, referential integrity, well defined behaviours, etc If you are doing it for 100k files and below you are using a Ferrari to pick up eggs in a corner store. If you are using it at 100k files and above, you are using a Ferrari to move a pile of paving stones one by one.
- herf 7y agoWonder what the number is with "noatime"? Every open is a write on a normal filesystem, but you can turn it off.
- wolf550e 7y agoBeware opening sqlite files from untrusted sources. https://research.checkpoint.com/select-code_execution-from-using-sqlite/ https://research.checkpoint.com/select-code_execution-from-u...
- sigzero 7y agoThat's true for everything.
- wolf550e 7y agosimpler file formats are less fraught, though they have fewer features.
- gridlockd 7y agoWhat's simpler than SQLite that would serve a similar purpose? If it's not a "battle-tested" format, it's still an issue no matter how simple the format is. Remember, your average C programmer can easily fit 11 buffer overflows in 10 lines of code.
- deleted 7y ago[deleted]
- microcolonel 7y agoReally depends on which filesystem too, you'll notice here that Microsoft's NTFS implementation is horrendously slow, HFS+ is several times faster, but still slower. Since they don't bother explaining which Linux filesystem they used, I suspect they mean EXT4, and the particular version of EXT4 in the kernel in that particular version of Ubuntu. The real news is: ext4 is about as fast as SQLite for small objects.
- Zenst 7y agoWhich is why for decades many dB offerings offered raw or cooked storage. Cooked being that they used the file system and raw being using the device directly. I'm not sure of the upsides and downsides today as I last worked in that area about 20 years ago, but was very much a case of raw a noticeable performance gain. But then you are equally tied into the vendors backup mechanisms.
- Spooky23 7y agoI ran a large at the time Informix implementation in the late 90s/early 2000s. Raw disk vs file system (Solaris UFS) performance was 35% faster on our transaction systems.
- Zenst 7y agoAs did I upon AIX and NCR towers. Did you find you had to offset the start block of the raw partition? As with AIX, even though the OS saw it as raw, it would stamp over the first 8k (iirc) with volume control data and with that, could easily corrupt a raw partition if you didn't factor in an offset.
- Spooky23 7y agoI don’t recall the details, but we used Veritas Volume Manager for managing the raw disk, and I’m pretty sure vxvm either hid that or had a driver that didn’t do it. Our restore run book was scripted and tight, so we may have been doing it ourselves, but I didn’t write the code or at least didn’t break it! Fun times.
- wayneftw 7y agoWow, so maybe instead of a node_modules folder, npm should use a node_modules.db?
- bob1029 7y agoThis sounds like a fantastic idea. You would go from 4000 directories and 50000 files to a single file with b-tree indices, hashes, etc. You could probably get a 100x speedup over the current approach.
- demosito666 7y agoEven better would be not to use it entirely - it'd solve far bigger problems with node.
- dymk 7y agoHere you go: https://github.com/guardianproject/libsqlfs https://github.com/guardianproject/libsqlfs
- Fnoord 7y agoThank you, I was reading the comments exactly to figure out if there was a FUSE sqlfs module. TL;DR this URL describes that, yes, there is. Why is this relevant? Because this way, you keep the flexibilities of a filesystem and, as a consequence of it being able to function like a filesystem, you keep the "power of Unix/Linux" ie. all your <asterisk>nix [1] tools keep working. [1] Calling it Nix confuses with NixOS...
- Const-me 7y agoThe fact that SQLite is much faster than file systems is not surprising at all. But there’s one surprising result there. > All machines use SSD except Win7 which has a hard-drive. And yet Win10 is much slower than Win7 in all tests (note they have latency on the graphs). How’s that possible? For a drive spinning at 5400 RPM, average random read latency can’t be smaller than 2.2ms, this is how long it takes to rotate the disks 180° which is an average. An SSD should do much better than that. I have a couple possible explanation. Either that particular Win10 machine, 2016 Lenovo YOGA 910, has _extremely_ slow SSD. Or there’s something wrong with software/drivers/config of the PC, like an antivirus, or wrong chipset drivers.
- karmakaze 7y agoThere's the other obvious explanation that because the Win7 machine has slower storage it automatically uses a larger cache than the Win10 machine that more than offsets the difference.
- Const-me 7y agoWindows kernel uses all free RAM as a file cache. Low priority one i.e. when an app wants to allocate RAM, the file system cached pages are evicted. Their Win7 test machine has 4GB RAM, Win10 16GB RAM. I think I know what’s going on. They don’t publish absolute numbers, they only publish result compared to SQLight on the same machine. Windows has approximately fixed overhead when opening files. Most of that overhead goes to access checks, NTFS security descriptors are way more sophisticated than 9 bits of security in Linuxes. With a fast disk that overhead dominates in the cost, SQLight doesn’t open any files while running the test, the DB already opened at startup. With a slow disk, that overhead is masked by large IO cost which affects both SQLight and NTFS.
- kukx 7y agoNitpick, but file permissions in Linux take normally 12 bits. You probably did not count SUID, SGID and sticky bit.
- c-smile 7y agoSlightly off the topic. In one of web applications (CRM alike) I was experimenting with SQLite-per-user approach. In that application user related data was clustered on per-user basis. So instead of single-db-for-all-users I had one-db-per-user. Performance gain was significant - around 25% for most of requests. I suspect that this is due the fact that index trees were significantly shorter for each particular user, data more local, etc. Yet db schema update and other batch requests can be made without stopping the server, just handle db files one by one. Just in case.
- derefr 7y agoThe formalization of this approach is https://github.com/biokoda/actordb https://github.com/biokoda/actordb — which is essentially a sharded document store where one type of “document” is an SQL-addressable SQLite database. Sadly, ActorDB seems to be inactive as a project—but the fundamental premise is sound. I’d love to see the concept reimplemented as e.g. a Redis module (since a Redis cluster essentially has the same “shape” as ActorDB’s custom distributed K-V store.)
- SiVal 7y agoThis is exactly the topic that made me read this thread. I have been wondering whether one sqlite file per customer was a good option for an online service where each customer needed only his own, private data but wanted to work on it from his desktop, laptop, or phone, with the option of occasionally downloading the file for additional backup. I just don't know enough about multi-tenant database approaches to know if this is a good idea or absurd, and I haven't found anyone talking about it. Any pointers to further insights would be greatly appreciated. Even a forum where (utterly unlike StackOverflow) I could ask such a question without already almost knowing the answer.
- carapace 7y agoSQLite in the browser... https://en.wikipedia.org/wiki/Web_SQL_Database https://en.wikipedia.org/wiki/Web_SQL_Database It was killed though. Derp.
- the8472 7y ago> The performance difference arises (we believe) because when working from an SQLite database, the open() and close() system calls are invoked only once Yes, open() can introduce significant overhead, especially when doing it sequentially on a remote filesystem, e.g. NFS. But that's using the filesystems in the most inefficient way possible, there are better ways to do it. E.g. you can pre-touch the files or even pre-open them in parallel and then point to /proc/self/fd/<N> instead, which turns an open() into a dup(). I was able to make some properietary software run 5x faster that way simply by feeding it already open file descriptors.
- muststopmyths 7y agostat to get filesize is a pathlogically bad pattern on Windows. If I remove the call to fileSize() in kvtest and instead replace it with 16k (since the max size in the post is 12k), I can significantly improve the time measured on Windows 10. Before: C:\temp>kvtest run test1.dir --count 100k --blob-api --count 100000 --max-id 1000 --asc Total elapsed time: 9.495 Microseconds per BLOB read: 94.950 Content read rate: 104.0 MB/s After: C:\temp>kvtest run test1.dir --count 100k --blob-api --count 100000 --max-id 1000 --asc Total elapsed time: 5.218 Microseconds per BLOB read: 52.180 Content read rate: 313.3 MB/s showing here the stable-ish numbers after a couple of runs of each version to let the cache warm up. Windows is a completely different beast than Unix and you need to know the beast to tame it. You might say that stat+open+read+close should be compared/measured together. In that case my answer would be that you would not read all files in a directory in this way on Windows anyway. You'd use overlapped I/O with buffers of FS cache granularity (which is 64Kb, unless it has changed in recent versions of Windows). It wouldn't matter for smaller files anyway (since the OS aggressively reads ahead when you open a file) and would be better for larger files. It is a bugbear of mine when I see complaints about Windows from people who never actually tried to optimize for the OS. reading blobs in Sqlite from db is still ~3x faster on my Surface Pro 2017 (don't call it Surface Pro 5!), but that's to be expected.
- SQLite 7y agoThanks for this. I did not realize that fileSize() was a performance issue on Windows. I'll attempt to update kvtest.c to deal with that, rerun the tests, and update the page, as I have opportunity.
- pdimitar 7y agoApologies for a hijack but since you're here, I really wanted to say thank you for sqlite! Saved me many headaches and made me a better programmer. You're amazing for creating it. And if you don't mind a question: are you guys up for making a strictly typed variant of sqlite? I'm aware it is going to be a completely different beast and many wouldn't expect backwards compatibility. Just curious if such a strongly-typed variant is on your radar at all.
- vr46 7y agoBillions of tech-years ago, BeOS made a filesystem that had database-like properties. Now, mainly because I have no idea what I’m talking about in this area, I don’t know if anything sprung from that into mainstream computing, so features like this from SQLite make the news. (It’s very cool, to be sure)
- gigatexal 7y agoSQLite really is the best of both worlds when it comes to files and databases: it is a file, one that can usually live entirely in memory; and it’s got all the awesome utility of SQL (even window functions too) that can be used very simply to do powerful things.
- realshowbiz 7y agoI remember a job interview where the take home project was to parse a log file and search/sort by various top attributes as fast as possible. I thought about writing something from scratch, but I knew that whatever I could optimize in an hour or two would be nothing compared to more robust tools that already existed. So I used sqlite to ingest the log once, and query it in various ways to produce the requested reports. The script was just a dozen lines long or so, with one dependency (sqlite pkg). The interviewer didn’t like this answer. didn’t say why. But I’m glad to see that I wasn’t way off base about how performant sqlite can be. My answer was of course not a prod solution, just an answer to a question with a narrow scope.
- otterley 7y agoThe interviewer didn't like the answer because it didn't answer the implicit question, which is how well you can write your own software. We know that you can load a table into SQLite and have it do the heavy lifting for you. But we're often not looking for software _users_ as much as we're looking for _engineers_. When we interview people, the answers we want often aren't real-world answers because we're trying to get a deeper understanding of how you think or how well you know the details of a complex mechanism.
- notyourday 7y ago> But we're often not looking for software _users_ as much as we're looking for _engineers_. What the applicant illustrated is that he is a much better engineer than the interviewer and the interviewer did not like it. Good software engineering is about leveraging existing robust tools in a new way, not about re-inventing a wheel while making is square. For me that would have been an insta-hire.
- otterley 7y agoI both agree and disagree with you. I agree that the answer was a good one in the real-world sense, and one that I would like an engineer to use under the right circumstances. I disagree that the answer demonstrated engineering prowess, however. Sometimes you have to assume the lack of existence of certain tools to understand how a candidate would have implemented the solution him- or herself to get a more thorough understanding of his or her engineering chops.
- dang 7y agoDiscussed at the time: https://news.ycombinator.com/item?id=14550060 https://news.ycombinator.com/item?id=14550060