5 ms·
This advice is good, but every startup I've worked with has run into lower hanging fruit than this even. Less scaling problems and more just organizational. Usu
by frollogaston 3mo ago
This advice is good, but every startup I've worked with has run into lower hanging fruit than this even. Less scaling problems and more just organizational. Usually what fixes that is:
1. Don't use an ORM.
2. Use serial PKs, not meaningful fields (article mentions this).
3. Use jsonb if needed, but sparingly.
4. Make your source of truth append-only, meaning you only insert, never update or delete. You can have secondary denormalized tables that are mutated, but that's only for performance/convenience and shouldn't be your sot.
5. Use connection pools, but be mindful of how many connections you're using. You probably don't need PgBouncer unless you've messed something up.
6. In code, avoid explicit transactions unless there's a clear reason you need them. Usually only need those for denormalized parts. Just take a conn from the pool, do something, commit, return conn to pool. If you're going to keep an xact open, never do long-running stuff in the middle like RPCs. Too often I see people leave xacts open without much thought. Edit: Also don't use SERIALIZABLE xacts almost ever.
7. Something is probably wrong if you're using explicit locking like SELECT FOR UPDATE.
8. Don't reinvent a type system by having a single table where each row can mean many different things depending on a "type int" enum col. Seems oddly specific, but for some reason someone always tries this.
9. Related to above, don't reinvent a graph DB, typically with "node"/"edge" tables that FK into themselves or in a cycle. 99% of the time what you're trying to do is easily solvable with regular normalized tables.
- atom_arranger 3mo agoCan you elaborate on 4 a bit, are you saying to always use event sourcing, or something like it?
- frollogaston 3mo agoYes, it's that. You do probably end up wanting to store some "latest" denorm tables at some point, but it takes surprisingly long to reach that point, and isn't hard when you get there. There are disadvantages to this, but it's a safe default. The alternative is possibly losing important data, finding out later you want historical records of things that are stored in kludgy separate tables, getting into more advanced locking situations, and having more complex DB migrations. Which I've had to pull teams out of many times.
- 0x696C6961 3mo agoUsing event sourcing instead of basic crud should go on a startup suicide guide ...
- atom_arranger 3mo agoI don’t have a lot of experience related to this so I’m just noting some things. Some people in this thread don’t seem to think it’s that hard or overcomplicated. When reading Designing Data-Intensive Applications my main takeaway was that event sourcing can make it easier to solve a lot of issues like performance, scaling, consistency, auditability, etc. It would be interesting to look into what a low overhead way of implementing CRUD with event sourcing in Postgres would look like, then decide if it’s too complex.
- frollogaston 3mo agoTry making Hackernews lite. Users can post, comment on posts, vote/unvote posts, and delete their own posts and comments. CRUD tables might be post, comment, maybe vote. Event tables might be create_post, delete_post, create_comment, delete_comment, vote, unvote.
- 0x696C6961 3mo agoDon't trust anyone who tells you event sourcing is simple to implement.
- edoceo 3mo agoWhat's wrong with select for update? I've found it useful in a few places. It is that fixed when there is an append only source of truth?
- frollogaston 3mo agoRight, that whole class of problems mostly goes away when you're not mutating your sot. I've actually never needed to use SELECT FOR UPDATE that I can think of. It does have its legitimate uses, but there are footguns that general SWEs not super familiar with DBs won't know about, like how it still doesn't prevent all types of race conditions unless you're in SERIALIZABLE mode.
- jvidalv 3mo agoFor games is a must have.
- frollogaston 3mo agoIf there's a high frequency of changes from a single user all being stored, probably need more specific approaches like that
- renegade-otter 3mo agoMost of the time you will save yourself a lot of grief by having a transaction decorator for each endpoint, as each HTTP call should be atomic. And then have another read-only decorator for RO transaction.
- frollogaston 3mo agoThat's an easy way to accidentally leave a xact open way too long. You might have enough connections in to support this normally, but when things go slightly wrong, they go very wrong.
- mrkaye97 3mo ago+1 to this - I've griped pretty often that FastAPI's documentation implicitly recommends this (https://fastapi.tiangolo.com/tutorial/sql-databases/#create-a-hero https://fastapi.tiangolo.com/tutorial/sql-databases/#create-...) by suggesting using dependency injection to manage database connections, only to start seeing connection pool exhausted errors as soon as the number of concurrent requests exceeds the number of allowed connections.
- frollogaston 3mo agoOh wow. Dep injection for DB connections is nasty.
- alfons_foobar 3mo agoI might be outing myself as a noob here, but... what is the (better) alternative?
- 0x696C6961 3mo agoYou inject the pool itself.
- 3mo ago
- kentm 3mo agoFor #4 I always tell people to assume 99% append only, but do consider the need for updates/deletes in edge cases. If any of the data is PII and you will be subject to GDPR (you probably want to be at some point) then you will need a way to hard delete it. A large portion of append-only datasets I’ve worked with have run into some edge case that required an update. Also if you’re doing an append only log plus mutable view then please use triggers or materlialized views. I ran into a few cases where the approach was to just update both tables and that lead to divergences between the two.
- frollogaston 3mo agoYeah, deletes need to be on the table (no pun intended) for PII redaction, and also emergencies where you manually do it. Both those situations are much safer when the DB is normally append-only.
- kentm 3mo agoAgreed. Usually an updated-on timestamp is sufficient to cover your bases without over-complicating the table. And your PII redaction is probably going to be shredding or nulling the fields instead of hard record-level deletes.
- manphone 3mo ago#8 is https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80... and it’s one upside is that it’s very flexible and it’s downside is literally everything else. If you can be 100% certain that all of the destination value types are the same then it can have compressibility benefits.
- sgarland 3mo agoI have no idea why you’ve been downvoted, as you accurately described EAV. I’m a DBRE who cares deeply about schema design, FWIW.
- frollogaston 3mo agoIdk, the comment is right. It is EAV. I've done a little bit of that when needed.
- j45 3mo agoNice summary - While it's not my first choice, or habit, in many use cases, using an ORM is still OK looking back in the start especially when the schema is being fleshed out prior to understanding what needs optimizing. It's trivial to start optimizing a query after taking it away from ORM. The new angle I think is the ability for LLMs to use ORMs given the documentation, etc. The only other thing I'd say is the benefits of running something that works with Postgres, such as Supabase, Hasura, etc. It really can be the best of multiple worlds, especially in the beginning in terms of having flexibility in one place.
- ozim 3mo agoDon't use an ORM. Highly debatable. When your highest cost is developers salaries. Don't reinvent a type system by having a single table where each row can mean many different things depending on a "type int" enum col. Easy to say, harder to not do when you have business requirements on table, customer pressure and budget already gone on discussing with DBA who maybe is right but you are burning money right here and right now. The same with point no. 9
- frollogaston 3mo agoIt was kinda debatable until people started Claude coding everything. Even before, I would've said every SWE should just know SQL, it's not much buy-in to understand the foundation of like your entire backend. Also I'm not a DBA if that's what you meant.
- InsideOutSanta 3mo agoLeaning SQL is arguably less dev work over the long run than learning an ORM and then learning how it works so you can fix performance issues.
- frollogaston 3mo agoYep, there have been extended periods of time where my entire job title might as well have been "ORM remover" because they backed themselves into a corner
- ozim 3mo agoDo you have any meaningful experience as a software developer? That’s a silly take. I somehow learned over the long run: SQL different flavors, couple of ORMs, multiple programming languages and multiple frameworks. Not counting different troubleshooting different operating systems and different applications I had to work with.
- frollogaston 3mo agoWe all learn whatever we need to learn to deal with the situation. I've had to learn more distinct ORMs than SQL flavors, even though you also need to know the SQL when you use an ORM. Doesn't mean I wanted to. However, each time a teammate wanted to use an ORM, I didn't call it silly or question their credentials.
- dwb 3mo agoI can certainly see the appeal of number four, but on more than a couple of systems I've worked on, it would have blown up the amount of data stored in a fair proportion of tables for very questionable benefit. It's a good technique to call out, but is it really right to dictate it for everything? And what is people's opinion of the reverse: source-of-truth in traditionally-modelled mutable relational tables, with a change log written out with triggers?
- frollogaston 3mo agoI've done it the other way before, sometimes a team choice rather than my own, and it's ended badly any time the changelog table is actually needed. Startups or just chaotic projects will change requirements and then need data that's only in changelog tables. The changelog tables in the meantime were only barely maintained as an afterthought, lacking FKs of course, and only useful for manual debug if even that.
- waisbrot 3mo agoThis is an excellent distillation. Yes, in practice you may find that one or two of these don't apply to your own special start-up. But probably they all actually do.
- frollogaston 3mo agoThanks, that's what I was going for.
- sklarsa 3mo agoThere's nothing wrong with an ORM if you want to move quickly and get something up-and-running, which is the case for pretty much every startup who needs an article like this. As long as you're aware of the typical footguns (N+1 queries) and understand your ORM's lazy-loading scheme, IMO it's worth the tradeoff of developing yet another way to manage and parametrize your queries. I'd rather spend the time building out my product than prematurely optimizing and overthinking my DB schemas at the earliest phases of a project.
- preg_match 3mo agoThe main problem is ORMs are more work, because you need to understand the ORM. That’s its own beast, each ORM is different, and they change between releases. But SQL is something you already should understand, so you get to reuse the knowledge. Also you can make SQL much more tolerable if you use migrations. That’s really where ORMs shine, but you don’t need the rest. Also query builders, although those also have a risk of abuse similar to ORMs. 99% of SQL should be static. That sounds like an absurdly high percent but it’s true if you use all the SQL features.
- poncho_romero 3mo agoIn the PHP back end I work on, I find the ORM immensely helpful because we need to instantiate objects to do things like permissions checks. The alternative seems like much more work. What am I missing with regards to ORMs being a bad idea?
- ozim 3mo agoIt is just „SQL people” crying out not knowing how to work with ORM. They always claim that devs who use ORM don’t know SQL. But I never seen or hired a dev that doesn’t know SQL and yet for each project we use ORM. I also never seen anyone claiming that you doesn’t have to know SQL and ORM is enough from the opposite side. If you really run into spot where your ORM breaks you can always drop to SQL. If you build project „SQL first” you robbed yourself from ORM upsides and you are bound to badly implement your own one in the long run.
- frollogaston 3mo agoThe issue is if you use the ORM, you still need to understand the DB it's on top of. There isn't much point in using such a leaky abstraction when it's easy enough to just use SQL.
- ozim 3mo agoI just wrote it at the end of my previous comment. You can use well known library that more people will comfortably using or given enough time you will build crooked, half baked ORM of your own.
- e12e 3mo agoI think orms are typically fine. Something like rails can even play reasonably well with legacy databases (but you might need to create a view or two to rename columns names that collide with "magic column names"). There are reasonable arguments for leaving most to the db; effectively exposing some VIEWs and FUNCTIONs as the application interface for any and all bindings. Like legacy java and greenfield php for example. I'd say it's different work rather than strictly more work.
- foo42 3mo agoOn point 4, is the general flow that an "update" would read the current latest, check whatever conditions, then rather than updating, insert a new record (all in a transaction), or is your append only sot more an ordered "log" of update requests with the result of any conditional operations requiring a replay (from at least a check point). Or something else entirely. I'm generally an immutable first, type developer but ive not had to do much schema design for a while and looking back to previous attempts we never hit scale to stress test my approaches.
- frollogaston 3mo agoIt's the first thing, read-then-insert, not blind insert. Also you don't always need to do the read and the insert in the same transaction.
- christophilus 3mo agoCan’t do RLS without a transaction, though, right?
- arkh 3mo ago> Don't reinvent a type system I'd like to add: stay away from using arrays and user defined types. They feel like a good idea at first, but will become a problem when using fetched data in your code. And another miss, if you're managing your servers: pgtune. The default postgres configuration is very conservative regarding resources so you can get good performance gains just by adjusting them to your server specifications.
- frollogaston 3mo agoAgreed. Jsonb is the only thing I'll use, and that's only if I'm getting/setting the whole col at once, not doing SQL that goes into the payload.