Speeding up DB seeding
I'm wondering if there is a quicker way for seeding my database. I'm working on software to manage self storage. I create leases for each storage unit, then I create invoices from the leases then payment records from those invoices. The leases and invoices take 47 seconds and the payment records take 80 mins. I think this is because I have to update each invoice individually to link it to the created payment record.
6 Replies
You chose to compile with the bot. One moment while I piece together your answer…
my schema:
the relevant part of seed.ts
To speed up your database seeding, especially when creating many related records (like leases, invoices, and payment records), you should leverage Prisma's bulk operations such as createMany, updateMany, and deleteMany. These operations are much faster than creating or updating records one by one, as they run in a single transaction and reduce round-trips to the database. For example, use createMany to insert multiple payment records at once instead of looping through and creating them individually. Similarly, updateMany can update multiple invoices in a single call, but note that bulk operations do not support nested writes or relations—so you may need to adjust your data model or perform some linking in a second step if necessary.
Here's a basic example for bulk creation:
If you need to update many invoices to link them to payment records, use updateMany, but remember it can't set relation fields directly—so you may need to batch updates by grouping invoices by the same update criteria.
Also, you can wrap multiple bulk operations in a $transaction to ensure they succeed or fail together, which is efficient and safe for large seed scripts. For more details and limitations, see the Prisma docs on bulk operations and batch/bulk operations.
If you need to seed with raw SQL for even more control and speed, you can use $executeRaw in your seed script, as described in the seeding docs.
In summary: use createMany/updateMany for bulk inserts/updates, wrap them in $transaction if needed, and consider raw SQL for complex or highly-performant
seeding tasks. This should drastically reduce your seeding time compared to individual record operations.
🤔 Alright, thanks for letting us know that there's still some help needed. A team member will reply to you shortly.
In the meantime, please let us know any additional info, questions, or which parts of the answer may need clarification.
How many payment records do you need to create?
80 mins is a lot 😅
I suppose I could do fewer years
Yes, are you on the latest prisma version?