r/PostgreSQL • u/easybits_ai • 4d ago
Projects Storing generated PDFs in Postgres vs object storage: where do you draw the line?
/r/n8n/comments/1y6s8tp/storing_generated_pdfs_in_postgres_vs_object/
26
Upvotes
29
u/yvrelna 4d ago edited 4d ago •
If you want to do blobs in the database, at least do them properly and use the proper blob/bytea type instead of base64-encoded varchar.
Unless you needed the blob to be part of a transaction, it's a bad idea to be storing a blob in the most expensive and hard to scale part of the system which is the relational database.
An object storage are much cheaper and easier to scale horizontally. A CDN can cache frequently downloaded blobs.
Even if you run your own file server, the OS and the web server can serve downloaded file from disk extremely efficiently with zero copy syscall like sendfile or copy_file_range.
By storing and serving a blob in the database, it means you're tying a database server connection, an application server worker, and the RAM needed to cache the file in-memory while the file is being downloaded and base64-decoded. All of which are unnecessarily expensive components when simpler, cheaper, and much more easily scalable solutions exists for not too much extra effort.
13
u/linuxhiker Guru 4d ago
Postgresql is not very efficient for binary objects. If your PDF is 100Mb, the connection will use at least that to deliver the PDF over the wire. Now multiply that by however many people want a pdf.
Use object storage and store the metadata in Postgresql
5
u/RevolutionaryRush717 4d ago
Maybe you got the cache part right.
The pdf seems to be ephemeral in nature, in that it always can be generated based on existing data.
Why that would take several seconds only you know.
So the question is why store it permanently at all?
Iff most users need it within, say, 24 hours after the workflow has completed, you can put the pdf in redis with a ttl of 24 hours.
If users return after weeks or months, couldn't they wait a couple of seconds for the pdf to be generated on demand?
3
u/manni66 4d ago
Why base64?
2
u/gevorgter 4d ago
it's rarely good idea, main reasons.
26
u/PrestigiousStrike779 4d ago
For me, I’d probably never do that because I don’t think blobs belong in the database. If I was going to do that I’d at least put it in a separate table so I don’t incur any performance penalties when reading the main row unless I actually wanted that data
1
u/eipi-10 4d ago
How big are the PDFs? I'd store them as bytea until it starts causing problems. Once (if) it does, start writing them to S3 instead and writing the keys - the one-time job to move the existing ones to S3 will be trivial
As a bit of editorial advice: There's never a "right" way to do things, only tradeoffs of different approaches.
1
u/cosmic_kpz 4d ago
please read: https://wiki.postgresql.org/wiki/BinaryFilesInDB
TLDR: Postgres store blobs as text or bytea (with it's “non-printable” octets), in a nut shell you are saving a gigantic wall of "text" in a table field.
Not a single relational database are able to handle this type of operation well, you should look for a TUSD service and store the file_id + hash, if existe multiple versions of the file of time you can thing in append/read only file ledger table with the timestamps.
No need for base64. It will only increase the database size, just don't! for MYSQL exists BLOB type for postgres BYTEA, anyway use TUSD
1
u/axtran 3d ago
Back in the day I worked for a company that did this. It was extremely resource wasteful.
Worst yet, it was essays that high school kids wrote during testing. You think anyone ever came back to look at these? Yet it became the bane of the legacy team to figure out how to backup the database successfully...
1
u/unexplored_explorer 3d ago
I’m still learning how Postgres and object storage work respectively, but I saw this one short from ‘Arjay The Dev’ on YouTube where he explained that the files themselves should be stored in object storage and file metadata and path could be stored in postgres
1
u/MongooseWonderful198 2d ago
If you keep them in Postgres, switch from base64 text to
bytea; base64 adds roughly one third to the payload before TOAST and backup costs. I’d also move the bytes to a separate one-to-one table so ordinary fact-sheet reads do not fetch or cache the document column.The line for object storage is less about file count than recovery and delivery. Restore one production-sized backup and measure it, then load-test a concurrent download burst. If database recovery or connection occupancy becomes the bottleneck, move the bytes and keep the object key, checksum and approval version in the transaction. For a handful of small PDFs, a measured Postgres design can be reasonable; it just should not be base64 in the hot row.
2
u/persicsb 4d ago
There is a thing specialized to store a large number of files, it is called a file system. Relational databases are specialized and optimized to store and query relational data.
1
u/AutoModerator 4d ago
AI Policy:
Linux is not one of those anti-AI projects, and if somebody has issues with that, they can do the open-source thing and fork it. Or just walk away., Linus Torvalds.
Mod decisions will be based on the quality of the content, not who or what generated it.
Sub Resources:
Youtube Channel
Free Postgres Webinars and Workshops
Discord: People, Postgres, Data
Join us, we have cookies and nice people.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Discordbothost 4d ago
The approved PDF is a record of what Finance signed off on. If you move it to object storage, save the object version in Postgres after upload succeeds and keep that version for as long as a backup could point to it.
1
u/krum 4d ago
pretty sure object storage is cheaper than db storage. i would go object storage from day one.
1
u/AintNoGodsUpHere 4d ago
Bruh, blobs don't belong in the database.
1
u/cthart 3d ago
What I like about storing objects in the database: transactionality, ACID etc
What I don't like about storing objects in the database: it generates a lot of WAL, backups etc
The "problem" with Postgres is it's all-or-nothing: you either get all the semantics and guarantees that a relational database gives you (with all of its overhead) or you have to manage it yourself: store a pointer in the database and the objects outside, and you have to manage keeping them in sync, backups, etc.
1
u/Tometzky 2d ago
I think the best is to store names and sha256 of files in the db and the contents indexes by sha256 in object storage. You'll have best of both words: transactions, ability to clone a database, restore from backup or with pitr from Postgres. But prod and test and dev can point to the same shared object storage like S3, so you don't need to clone it or restore from backup. Database backups are not cheap per GiB - at least not in AWS RDS. The only problem is when can you delete the file - you have to make sure no system or database backup point to it and you have to backup object storage separately (but don't have to do this at exactly the same timestamp as the database).
1
u/dariusbiggs 2d ago
files go into object storage, never inside a database.
1
u/hbliysoh 23h ago
If your database isn't too busy, this can work. PDFs don't need to be big. But if you're trying to scale, object storage is the only way to go.
1
u/thecavac 21h ago
Storing vs recreating isn't strictly an either/or question.
I'm the main developer of a cashregister software. Certain documents i have to store "as is" (virtual hardcopy) permanently over the full livetime of the cash register (financial regulations). Others, like normal invoices i am allowed to re-print from raw data.
Invoices get reprinted mostly in the first seven business days, like when the customer lost their copy or there is a financial audit that wants a hardcopy of all of yesterdays invoices. After that, reprints are pretty rare.
So i store the printed documents in the database for 14 days or so (depends on what kind of document), after that they get uncached and go through the full full printing queue again if a hardcopy is requested.
(Technically: If a reprint request comes in, i check if there is a cached copy. If yes, send that to the printer. If no, i set the is_printed flag of the database row back to false, then the printing system kicks in and recreates the document)
So basically, the documents that are most likely to be reprinted are cached, then aged out when the likelyhood of a reprint request tails off.
I always store these in the database itself. It may not be the most efficient solution performance-wise, but it's a cash register, so the total number of invoices seldomly breaches a million in a big installation. But it makes all the handling much easier and more convenient, especially when it comes to backups and restores.
Especially when running tests and bugfixing customer-specific problems, a simple pg_restore let's me recreate the full customer setup and run the dev system with the *exact* data the customer has on their system. And since there is no external cache to deal with, i can easily switch between projects and test setups just by changing the database name.