Shardines: SQLite3 Database-per-Tenant with ActiveRecord

https://news.ycombinator.com/rss Hits: 15
Summary

A Can of Shardines: SQLite Multitenancy With Rails · 25 Apr 2025 There is a pattern I am very fond of - “one database per tenant” in web applications with multiple, isolated users. Recently, I needed to fix an application I had for a long time where this database-per-tenant multitenancy utterly broke down, because I was doing connection management wrong. Which begat the question: how do you even approach doing it right? And it turns out I was not alone in this. The most popular gem for multitenancy - Apartment - which I have even used in my failed startup back in the day - has the issue too. The culprit of does not handle multithreading very well is actually deeper. Way deeper. Doing runtime-defined multiple databases with Rails has only recently become less haphazard, and there are no tools either via gems or built-in that facilitate these flows. It has also accrued a ton of complexity, and also changes with every major Rails revision. TL;DR If you need to do database-per-tenant multitenancy with Rails or ActiveRecord right now - grab the middleware from this gist and move on. If you are curious about the genesis of this solution, strap in - we are going on a tour of a sizeable problem, and of an API of stature - the ActiveRecord connection management. Read on and join me on the ride! Many thanks to Kir Shatrov and Stephen Margheim for their help in this. The advantages of the “database per tenant” If you have a tenanted application (your “tenant” is a subgraph of your data model that can function independently, and mostly references other entities from within itself), you have a number of ways to approach an architecture like that. Imagine we have a system where the tenant is a Site. That system is some kind of end-user-serviceable CMS, and users own multiple Sites and can manage pages, media and other items within a Site. The data model will be as follows: class Site < ActiveRecord::Base end class Page < ActiveRecord::Base belongs_to :site has_many :media_blocks ...

First seen: 2025-04-27 13:16

Last seen: 2025-04-28 03:18