r/PostgreSQL • • 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

62 comments sorted by

29

u/yvrelna 4d ago edited 4d ago • Bravo

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. 

Where would you draw that line? 

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. 

0

u/easybits_ai 1d ago

Thanks so much for sharing this! This is really valuable, and I'll definitely look into proper object storage as an alternative. Since the project is still in its early stages, it's also a good time to make that change if needed.

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

1

u/easybits_ai 1d ago

Good point! The PDFs are only a few KB each, though, so I think I'll stick with storing them directly in the database. I'll just switch the setup to bytea today.

-3

u/RevolutionaryRush717 4d ago

Why would the pdf be more than a handful of kB?

Why would PG not be efficient for such binary objects?

3

u/Traditional_Nose3120 4d ago

Embedded high res images, or just a plain PDF from a scanner, will get you the multi megabyte blobs faster than you think.

Then the database gods smite you and you have a 700gb backup to restore. Explaining the resulting downtime in a root cause analysis isn’t fun. Been there, done that, have the tire treads from the product manager’s bus on my back to prove it.

S3 style storage for blobs, and a pointer to the S3 storage in the database. Use the right tool for the right job, and keep your back tread-free.

1

u/easybits_ai 1d ago

I definitely see the benefit of this approach when dealing with large PDFs, but the ones I'm working with in this case are 200 KB at most. So for now, I'd switch from base64 to bytea to reduce storage overhead, but I think keeping them in the database should still be fine given the relatively low volume. Nevertheless, thanks so much for sharing your insights!

1

u/RevolutionaryRush717 4d ago

Is that according to OP's case?

2

u/GoTheFuckToBed 4d ago

in real world people take pictures of their documents and combine it into a 40mb pdf

0

u/RevolutionaryRush717 4d ago

Interesting.

I was under the impression that OP generated the pdfs from text and numbers he had available in the database, maybe by using a templating engine that renders to pdf.

Your approach of replacing that with an initial print to paper step, followed by a manual photo of the pages, followed by a conversion to pdf, is fascinating.

What motivated your proposal of an alternative to automation?

1

u/easybits_ai 1d ago

You're right! That's exactly what the workflow does. And while I understand that what u/GoTheFuckToBed is saying is valid in real-world scenarios, I'm generating these PDFs directly within the workflow, and they're only around 200–300 KB each. Maybe I should have mentioned that in the original post.

8

u/SirApprehensive7573 4d ago

we have differents pdfs

I have some pdf that is ebooks, that the size is around 200MiB.

-2

u/RevolutionaryRush717 4d ago

And why are they so large?

Is it a reasonable assumption that all of OP's pdfs will be 200 MB?

Even then, how many would it it take to become problematic?

7

u/linuxhiker Guru 4d ago

Pdfs can be:

Full color

Contain images

Contain videos

Etc....

PDF is not just compressed PostScript anymore

-1

u/RevolutionaryRush717 4d ago

So how should OP fashion their pdfs to require as little storage as possible while still satisfying business requirements?

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?

2

u/easybits_ai 1d ago

Hey there! What actually happens is that, at the end of each month, users download the PDFs for all their transactions. That can mean up to 100 documents. At around 20 seconds per document, that's more than 30 minutes of waiting time just for the PDFs to be generated, which is definitely too long.

3

u/manni66 4d ago

Why base64?

4

u/RevolutionaryRush717 4d ago

Exactly, we have bytea.

1

u/easybits_ai 1d ago

Thanks for sharing this! I went with base64 because it seemed like the most straightforward solution at the time, but bytea sounds like a good alternative. I'll definitely take a closer look at it today!

What would you say are the main advantages of using bytea over base64 in your experience?

2

u/gevorgter 4d ago

it's rarely good idea, main reasons.

  • If you keep PDFs in DB your DB size will balloon very quickly. Backup restore will take forever. So if your server dies you are looking at hours/days of downtime simply because of your DB size.
  • I know storage is cheap but not unlimited. We keep our PDFs on S3 and simply redirect browsers to it (pre-signed url that is live for 1 min). S3 gives you unlimited storage while your DB lives on your local drive.

1

u/easybits_ai 1d ago

Thanks so much for the honest feedback! I really appreciate it!

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 

17

u/lhauckphx 4d ago

The size of your backups/dumps start to get out of hand pretty quickly.

1

u/RevolutionaryRush717 4d ago

Why would size matter?

What does "pretty quickly" mean in actual numbers?

Have you considered physical vs logical backups?

2

u/cosmic_kpz 4d ago

Why would size matter? read/write latency What does "pretty quickly" mean in actual numbers? 1gb is already a demoniac size for blobs,

please read: https://wiki.postgresql.org/wiki/BinaryFilesInDB

TLDR: Postgres store blobs as text or bytea (with it's “non-printable” octets)

2

u/RevolutionaryRush717 3d ago

Are we still talking about backups?

2

u/cosmic_kpz 3d ago

I don't get the down votes, but anyway: The big problem with large backups is downtime, if downtime it's not a concern, like: You don't have a operation running 24/7 (production line) it's may not be a problem, for example: A office that runs only from Monday to Friday.

So again: if you can, keep the database smaller as possible and the downtime to restore backups will be also smaller.

2

u/spigotface 3d ago

Blobs can have a home, but my best use case for that is storing uuids in sqlite (I know this is a postgres sub). Uuids as blobs take up half the space as storing them as strings.

2

u/yvrelna 2d ago edited 2d ago

In postgres, you can just store uuid with the UIID type. 

When people advise against blob, it's not actually anything to do with the literal blob datatype. It's more about advising against storing large, opaque data that the database doesn't really have the ability to query on, i.e. Binary Large OBject. bytea/blob is the most common data type that are abused in this manner, but not all bytea/blob columns are the bad kind of blob, but you could've also stored such blobs in other columns like text or json columns.

A UUID is not a large binary object. It's a tiny binary data that has a fixed 16 bytes length. That technically it is stored as blob in sqlite is simply because sqlite has a rather simplistic type system, but it's not really the kind of blob people were advising against. 

1

u/ngqhoangtrung 3d ago

doesn’t Postgres have TOAST which improves performance for querying tables with blob column?

3

u/yvrelna 3d ago

TOAST improves the performance of blob column. It still doesn't make it a good idea.  

I outlined the main issues with blobs in my comment. The most core issue with storing blobs in a database is something that isn't really fixable within the database server itself. 

2

u/ngqhoangtrung 3d ago

great point! I can’t imagine storing blob in rds either, always store a reference to an s3 object. Your comment really puts this into words

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/easybits_ai 1d ago

The PDFs are between 200 and 300 KB each, so I think the base64/bytea approach should work fine for this use case. Nevertheless, I was curious to hear what other builders think about it.

Also, thanks for the editorial advice! Most of the time, I'm just writing these posts in between projects, so bear with me. I'll make sure to keep that rule in mind going forward.

1

u/eipi-10 1d ago

Nice! Yeah, I would just put them in bytea until you start running into problems, which you likely never will - just for the back of the napkin math: at 500kb per pdf, if you had 1M of them, you'd be using ~500GB of disk space

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

2

u/easybits_ai 1d ago

Thanks for the tip! I'll definitely check out 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/easybits_ai 1d ago

Damn, that sounds like a really stressful project, especially knowing that all the work you're putting in might never even be looked at again. Thanks so much for sharing your experience!

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/easybits_ai 1d ago

That sounds like a good approach, especially when dealing with large documents. Thanks so much for sharing!

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.

1

u/easybits_ai 23h ago

Thanks for the tip, u/MongooseWonderful198! I've already switched to bytea this morning and moved the blobs into a separate table. Since the PDFs I'm storing are only around 200 KB each, I think keeping them in the database should be fine for this use case.

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.