back
90 comments
> Maybe one day I’ll learn to read a query plan.

With SQLite's `.expert` mode you can delay that day a little longer: https://www.sqlite.org/cli.html#index_recommendations_sqlite...

  sqlite> CREATE TABLE x1(a, b, c);                  -- Create table in database 
  sqlite> .expert
  sqlite> SELECT * FROM x1 WHERE a=? AND b>?;        -- Analyze this SELECT 
  CREATE INDEX x1_idx_000123a7 ON x1(a, b);

  0|0|0|SEARCH TABLE x1 USING INDEX x1_idx_000123a7 (a=? AND b>?)

  sqlite> CREATE INDEX x1ab ON x1(a, b);             -- Create the recommended index 
  sqlite> .expert
  sqlite> SELECT * FROM x1 WHERE a=? AND b>?;        -- Re-analyze the same SELECT 
  (no new indexes)

  0|0|0|SEARCH TABLE x1 USING INDEX x1ab (a=? AND b>?)
Also wrt

> My approach so far has been to just do these cleanup operations in small batches so that I don’t need to do database queries that take more than 5 seconds to run. This whole experience has given me more of an appreciation for why someone might want to use a “real” database like Postgres which can have more than one writer at the same time though.

The advice for those " “real” " databases is generally to also do cleanup operations in small batches, they just tend to make it less obvious you're doing something unperformant in the smaller case. You're more right than you thought!

Another side effect of deleting 10 million rows in some databases (e.g., Oracle) is that the database writes out 10 million rows' worth of undo, which can swamp the disk space set aside for archive logs if you can't back it up and clear it off fast enough. Committing more frequently help, but if you have large databases and regularly need to purge, the best way in my experience is to use partitioning. Dropping the oldest (or whatever) partition is nearly instant and painless.

I wasn't clear exactly what the author was doing. "The worker crashes because it couldn’t write to the database and the VM shuts down" - why would the VM shut down? I assume VM here means the Virtual Machine (OS).

I've worked with large MySQL databases that used row-based replication and things like an UPDATE or DELETE that affected millions of rows had to be applied in batches there, because otherwise one SQL query might result in a million updated rows needing to be sent to all of the replicas at once.
Looks similar to EXPLAIN QUERY PLAN: https://sqlite.org/eqp.html

Raw EXPLAIN dumps bytecode, which is usually much more verbose than you want. EXPLAIN QUERY PLAN dumps a summary.

> they just tend to make it less obvious you're doing something unperformant

Is this being positioned as a strength, in your comment?

> I’ve been backing up to AWS, which is always a pain because it’s annoying to navigate the AWS console to generate credentials.

I got so annoyed with that a few years ago that I ended up building a whole tool just to solve that one problem:

  uvx s3-credentials create my-existing-s3-bucket
This spits out read-write credentials that are scoped JUST for that bucket. You can add --read-only or --write-only to have credentials that are further locked down, or even add --prefix foo/bar for credentials that can only read/write keys that start with that prefix within the bucket.

> Maybe one day I’ll move away to some other S3-compatible alternative.

I've used Restic with Cloudflare R2 and it worked great.

A more general solution for dealing with complex AWS services is learning just enough terraform to let LLMs do the rest. It also makes it much easier to tear stuff down later as you won’t need to remember what you created.
Prior art also has https://litestream.io/
this is pretty brilliant, aws cli should sherlock this.

when would you want write only?

As a database person, this was hard to read. I wanted to find out what the problems are and solve them.

A db table with only 10k rows? Even a full table scan should be extremely fast.

And with SQLite - which I assumed runs in-process, but even if not, surely is running on the same physical server? Faster still.

Of course, the magic phrase in my head is “create index”.

I hope Julia posts an update!

Edit: I highly suspect the “slow deletes” problem is a classic “n+1” problem suffered by many ORM users, until they come to understand more about the underlying db interactions.

I realized that in the age of LLMs I appreciate Julia’s writing even more. Authentic exploration as an antidote to overconfident know-it-all generated junk articles.
I run my backups like this:

    OUT="${i}.sql.zst"
    PART="${OUT}.part"
    sqlite3 -readonly "${i}" .dump | zstd --fast --rsyncable -v -o "${PART}" -
    mv "${PART}" "${OUT}"
That doesn't block writers (when the writer uses WAL), and gives me a dump that's compressed well while also being easy to sync. My Home Assistant DB is 1.8GB, my dump is 286MB compressed, and I'd guess 90% of that is consistent from one day to the next.
> That doesn't block writers (when the writer uses WAL)

Neither does VACUUM INTO or ".backup" (which uses the backup API) or sqlite3_rsync or litestream.

What do you backup from your Home Assistant? The default backups are huge, but I finally settled for just the config and I leave the videos and caches off. I also leave off all the HACS downloaded repos. I'm wondering if I'm missing out by doing what I'm doing.

What's in the DB that makes the HA DB that big? You keep lots of historical time-series?

Nice. I switched to .backup for live DBs because .dump locked me out once. The .part + mv trick is clean though.
As for the DELETE issue the easy solutions are:

-Delete it batches

-Delay between batches

-Preload the rowids before deleteing with SELECT (Select does not block)

Additionally if data was added sequentially primary to the same table the data is likely stored this way in the file and deleting it in this or in reversed order can be faster (depends on storage medium and other factors).

Row ID preloading is an extremely effective technique—and not just for SQLite. I’ve also used it to great effect on massive Aurora MySQL or Postgres clusters since I could send the SELECT to a replica, and the whole point of deletions was that index memory pressure from the row filtering was putting tons of CPU and buffer cache pressure on the db.

If you’re in a situation where partition pruning or other strategies for getting useless data out of the hot path don’t make sense, this is a killer strategy.

Diving a bit more into databases than your current comfort level/current job demands remains a great way to level up.

I've worked with many web developers who get mental blockage around DB tooling (granted, I have similar mental blockage when it comes to some operations stuff like K8s), and you can go far in life without really having to ask _that many questions_.

But going in and finding out how your SQL turns into data gotten from disk/written to disk is very helpful in just "knowing" what might be a decent idea. That and understanding your DB's locking system (or lack thereof...).

Figuring that stuff out can help reduce the surprise level when you can't seem to get a "simple COUNT" working quickly in Postgres or the like...

> and presumably other things?

Various statistical views over the value distributions of the indexes, so that the planner can estimate how useful (selective) the index should be.

sqlite_stat1 just gives an average (number of records in the index, and average number of records per value), and if enabled sqlite_stat4 stores histogram data.

> I didn’t care to investigate further

and

> my best guess

and

> and presumably other things?)

and

> maybe there’s a bunch of Python code running inside a transaction

Basically, this article has no substance. The author didn't bother to learn anything, didn't look things up. And is then wildly guessing, sometimes wrong.

This is BTW the reason why (as a Debian user) if I search something Linux related and a Ubuntu forum pops up, I don't even open that anymore. Sure, Ubuntu is similar to Debian, but the amount of wrong guessworks in these forums is hefty. I however usually open the Arch Wiki pages, despite Arch very != Debian. But the articles there are written by knowledgeable people.

Julia Evans is an extremely knowledgeable person.

She's also one of the best out there at demystifying technology and helping people understand what solving problems actually looks like.

This article doesn't pretend to be a world expert's take on using SQLite. The clue is right there in the title - "learning a few things about running SQLite" - which sets expectations right from the start.

The wider message is consistent throughout all of her writing. You can do this stuff. Here are simple practices to show how to figure out problems and build your knowledge. You don't have to know everything, and you certainly don't have to pretend to know everything. Sharing what you've figured out so far, in as clear a way as possible, is a virtue.

I actually think the article is great - it shows the experience of someone who is a good approximation of a smart user that uses the tech. The posters focus is clearly on running the website, and these are the sorts of things that trip up everyday users that don’t spend their day in these tools.

Off the top of my head, yesterday in work I used 2 programming languages, 2 build systems, a cloud provider, a secrets manager, a very intricate framework for client server communication in both languages, plus my VCS, editor and CI tool. That’s a fairly typical set of tools to use for one feature for me, before you go into the weeds of OS versions, specific runtime versions, databases, reverse proxies, caches, and the domain logic!

If I went deep on every single thread exposed to me, I’d never get anything done, so I have to choose my battles just like OP has done here

The Arch wiki is one of the best Linux-related resources out there. I used to look things up there all the time back when I was running Mint (which is basically Ubuntu under the hood). Ironically, now that I'm actually running Arch I think I'm looking things up on the Arch wiki less often than when I was running Mint.
Don’t tell me you you found a load bearing seam. Honest take, the blast radius of that footgun muestra have read impressive before it was posted
the best thing about sqlite is that it's one of the few pieces of software where reading the documentation makes you a better engineer instead of just a more confused one
Litestream is super interesting, I managed to get it to run with S3 as a backend. Making apps with sqlite backends (there are a _lot_ lf them) almost stateless, at least no filesystem stare. I feel like s3 state is much more manageable, backups and syncing is done by the provider.
If you are worried about the cleanup operation having python code running in it, maybe you could use the SQLite CLI to run that operation instead.
If you're not using them, adding in silk and/or debug toolbar to your django app will be able to get some good automatic reporting and guidance on performance issues.
An additional note running SQLite in production:

SQLite gets really slow when using very large BLOB's (100+ MB). I ended up having to store the BLOB's externally and refer to them from the SQLite DB. Not ideal of course (the BLOB's are not transacted) but works OK in practice using hashing/checks etc. to detect and handle invalid BLOB's.

I wonder if the ORM deletes were slow due to looping through a list calling delete on each object vs having a bulk delete method which accepts a list of IDs?
# Upload backup to S3 # Sometimes the backup gets OOM killed and so it stays locked, do an unlock.

An standard S3 upload like "aws s3 cp" doing OOM is surprising (to me)

Maybe the backup job should periodically restore into a temporary DB and run PRAGMA integrity_check. Theoretically should help
Great tip about `analyze`!

I just ran it on my self-hosted MediaWiki installation and it took the search from seconds to milliseconds.

What does he mean by "I do usually try to monitor them with a dead man’s switch.", when talking about backups?
Dead-man's switch means triggering when something doesn't happen. (The name comes from a switch that an alive operator would need to hold in such a way that if they died they would stop holding.) So in this case she means that her monitoring will fire if there wasn't a successful backup within some configured period of time.

I assume this is opposed to alerting when the backup job fails, which is an issue if the job never runs, or hangs forever, or crashes in a way that doesn't trigger your monitoring.

However I don't see how any of this solves the issue of not testing your backup. Because you can definitely have a backup task succeed regularly but the thing it is backing up is still unusable.

I don't call it a "dead man's switch", but I absolutely monitor some directories for new newest file. If the backup monitoring script doesn't find a file less than 24-ish hours old in the backup destination directory at any time it should send me an alert.
(she)
"Maybe one day I’ll learn to read a query plan."

Query plans aren't that hard to read! [0]

0 - https://xkcd.com/2501/

Database is locked got me too. Setting busy_timeout to something nonzero fixed most of it.
It was a great read Julia. I have also been using SQLite for my Wingman AI bot but had not explore much not for a website or another project. Your notes will be helpful, for sure. Thanks
IMHO for a small DB I’d encourage sending out an email on each successful backup to ensure it’s completed successfully as a safety check, and zipping it up and emailing it to a known account even. With inboxes being able to take gigabytes, it’s a no brainer. This can be done daily or weekly.

And yes, never allow the files to be deleted from outside. The transfer is a one way valve. If uploading, it’s a write-only operation, no delete unless the file has meta data for expiry.

It's great! However, it's only meant for local systems. Once you need to connect over a network or robustly handle simultaneous requests, you need something like postgres.
Is it me or this is one of the worst and knowingly less informed articles that has hit HN in a while?
Why not try a real database like Postgres? It's not as light-weight, but when operations get complicated, real databases are much easier to work with. I had a website that started with SQLLite, but when it got complicated enough, I spent two days to migrate the whole thing to Postgres. With current LLM coding agents, it's not that hard.