Latest / CyberSecurity Summary / High Performance PostgreSQL for Rails: Reliable, Scalable, Maintainable Database Applications
Transcript
- 0:00Speaker 1: Welcome to the deep dive. This is where we take
- 0:01Speaker 1: a whole stack of complex information, research notes articles and
- 0:06Speaker 1: really boil it down to the essentials for you. And
- 0:08Speaker 1: today we're plunging into a topic that's just well critical
- 0:11Speaker 1: for any serious developer, high performance Postgres School, specifically within
- 0:15Speaker 1: Ruby on Rail's applications. Our mission really is to give
- 0:19Speaker 1: you those key insights that will make your apps faster,
- 0:22Speaker 1: more reliable, definitely more resilient. What's kind of cool is
- 0:25Speaker 1: that our main source here is actually a beta book.
- 0:27Speaker 1: It's still being developed, so you're getting some really cutting edge,
- 0:30Speaker 1: very practical info straight from the trenches.
- 0:32Speaker 2: You might say, yeah, and that's exactly why this is
- 0:35Speaker 2: so relevant right now. Getting really good at postgreschool and rails.
- 0:39Speaker 2: That's not just helpful for your career, it's massively in demand,
- 0:44Speaker 2: right Just think about it. A Hired survey from twenty
- 0:46Speaker 2: twenty three it found Ruby on rails was actually the
- 0:48Speaker 2: most sought after skill. We're talking one point six y
- 0:52Speaker 2: four times more interview requests if you know your stuff, wow.
- 0:55Speaker 1: One point six four times Yeah.
- 0:57Speaker 2: And Postgres School it's consistently winning wards. It was number
- 1:01Speaker 2: one in the twenty twenty two stack Overflow survey for
- 1:04Speaker 2: most used database among pros and it's topped the dB
- 1:08Speaker 2: engine's ranking three times. So yeah, the time spent learning this,
- 1:12Speaker 2: it's it's definitely high impact knowledge.
- 1:15Speaker 1: Okay, all right, let's get into it. Then. Before we
- 1:16Speaker 1: can even you know, talk about performance tuning, we need
- 1:19Speaker 1: someone to actually do the tuning. We need a test bed.
- 1:22Speaker 1: So this source material. It introduces a fictional app called
- 1:25Speaker 1: ride share. What exactly is that? And I guess how
- 1:29Speaker 1: does it help us learn this stuff?
- 1:31Speaker 3: Right?
- 1:31Speaker 2: So ride share is it's basically designed as this simplified
- 1:34Speaker 2: API only web app. Think of it like a mini
- 1:37Speaker 2: Uber or Lyft. You know, it's got the core active
- 1:39Speaker 2: record models you'd expect drivers, writers, trips, trip requests.
- 1:43Speaker 1: That's worth thing and active record just quickly, that's the RM, right,
- 1:46Speaker 1: the object Relational mapper in reels exactly.
- 1:48Speaker 2: It's the magic layer that connects your Ruby code, your
- 1:50Speaker 2: classes directly to the database tables. And it really leans
- 1:54Speaker 2: into that rails philosophy of convention over configuration.
- 1:57Speaker 1: Ah right, like driver model maps to driver's table.
- 1:59Speaker 2: Automnate precisely, you don't have to spell it all out
- 2:02Speaker 2: and for managing schema changes rideshare uses the standard rail
- 2:05Speaker 2: stuff dbstructured dot s cool along with active record migrations
- 2:09Speaker 2: under the hood that uses pg dump to capture the structure.
- 2:13Speaker 1: You know, one thing I found really valuable in the
- 2:15Speaker 1: source was this strong push to set up and use
- 2:19Speaker 1: postgrass School locally, like really, make it your own little lab.
- 2:22Speaker 3: Totally. It's not just theory.
- 2:25Speaker 2: Having it run locally gives you complete control a safe
- 2:28Speaker 2: space to experiment, which, let's face it, is absolutely essential
- 2:32Speaker 2: when you're messing with performance settings. You don't want to
- 2:34Speaker 2: test this stuff live, definitely not, and getting rights you're
- 2:37Speaker 2: running is designed to be pretty smooth. You use Homebrew
- 2:40Speaker 2: urban v for your Ruby version, Butler for gems, and
- 2:43Speaker 2: then just the standard binrails commands dB do I create, dB,
- 2:46Speaker 2: DOT migrate, dB console simple stuff. Once you set up,
- 2:49Speaker 2: you immediately start bumping into core postgred school ideas like
- 2:54Speaker 2: SQL being a declarative language.
- 2:56Speaker 1: Okay, what does that actually mean? Declaraty?
- 2:58Speaker 2: It just means you tell postgres School what you want,
- 3:00Speaker 2: like get me all the trips from yesterday, and you
- 3:02Speaker 2: don't specify how to get it. Postgrescool's optimizer, its brain
- 3:06Speaker 2: figures out the most efficient way to execute that request.
- 3:10Speaker 1: Ah, so you declare the result. It handles the process
- 3:13Speaker 1: like ordering food, exactly.
- 3:15Speaker 2: Like ordering food, and the how it figures out that's
- 3:18Speaker 2: the query execution plan. It's like the database's internal recipe
- 3:22Speaker 2: for fetching your data. Plus you've got functions built in
- 3:25Speaker 2: ones and ones you can define yourself, which really let
- 3:28Speaker 2: you push complex logic down into the database itself. Seriously,
- 3:33Speaker 2: we can't stress this enough. Get ride share set up locally.
- 3:36Speaker 2: It really is the perfect lab for practicing everything we're
- 3:39Speaker 2: about to cover.
- 3:40Speaker 1: Okay, performance lab established. Ride Share is running locally, safe
- 3:43Speaker 1: space acquired. But to really know what's going on, we
- 3:46Speaker 1: need tools to look inside Postgres school, Right, how do
- 3:49Speaker 1: we peak under the hood.
- 3:51Speaker 2: Yeah, the piece grows command line tool is kind of
- 3:53Speaker 2: your main entry point there. There are a few meta
- 3:55Speaker 2: commands you'll use all the time, like a cantillybax that
- 3:58Speaker 2: toggles This expanded view makes query results way easier to read.
- 4:01Speaker 1: Oh yeah, that's super helpful.
- 4:03Speaker 2: And e is great. It pomps your current query and
- 4:06Speaker 2: your text editor life saver for complex SQL. Then there's
- 4:10Speaker 2: EEL to just list your databases. You can also customize
- 4:13Speaker 2: PSQL using a timicustl RC file add aliases, change the
- 4:17Speaker 2: prompt whatever makes you comfortable, and for enabling some really
- 4:21Speaker 2: powerful extensions like PG stat statements, which will definitely circle
- 4:24Speaker 2: back to you need to edit your postcrisql dot com
- 4:27Speaker 2: file specifically the shared preload library is setting.
- 4:30Speaker 1: Ah, okay, and that canfig change needs a restart.
- 4:33Speaker 3: Right that specific one does.
- 4:34Speaker 2: Yeah, Shared preload libraries needs a full postcresco restart to
- 4:37Speaker 2: take effect.
- 4:38Speaker 1: Got it? So okay, we can configure things, but how
- 4:41Speaker 1: do we see what the database is doing? Like right now?
- 4:44Speaker 1: Is it just log files or is there a more
- 4:46Speaker 1: direct way? I remember this one time a query just
- 4:50Speaker 1: ran forever almost took down the whole app. If only
- 4:52Speaker 1: I'd known about PG stat activity. Oh.
- 4:53Speaker 2: Absolutely, PG set activity is exactly that. It's your real
- 4:55Speaker 2: time dashboard. You see every connection, what state it's in active, idle,
- 5:00Speaker 2: maybe crucially idle in transaction, and you see background processes too,
- 5:04Speaker 2: like autovacuum, so.
- 5:04Speaker 1: You can spot those long running queries.
- 5:07Speaker 3: Yep.
- 5:08Speaker 2: You can see the curry text, find its process idea
- 5:10Speaker 2: the PID, and then if you really need to, you
- 5:12Speaker 2: can try to cancel it gracefully with pg cancel back
- 5:15Speaker 2: end or in an emergency, terminate it with p determinative
- 5:19Speaker 2: back end. Use that last one carefully.
- 5:21Speaker 1: Though right termination is a bit heavy handed.
- 5:24Speaker 2: It can be Now this ties into understanding pessimistic locking.
- 5:27Speaker 2: It's what postgrescool does by default. You'll see shared locks
- 5:31Speaker 2: and exclusive locks. The main takeaway you really want to
- 5:34Speaker 2: minimize how long you hold exclusive locks because they block
- 5:38Speaker 2: everyone else trying to access that same data.
- 5:40Speaker 1: And that can lead to deadlocks.
- 5:42Speaker 3: Exactly.
- 5:43Speaker 2: Deadlocks are the worst case scenario, two transactions waiting for
- 5:47Speaker 2: each other, stuck forever. Postgres will will detect and break them,
- 5:51Speaker 2: but it means one transaction fails. You can see livelock
- 5:54Speaker 2: information using the peaklocks view.
- 5:56Speaker 1: Okay, so lots to monitor. How about experimenting safely?
- 6:00Speaker 2: These source suggest using generate series to create lots of
- 6:03Speaker 2: fake data. You can do this in a separate experiment's database.
- 6:05Speaker 2: It's a great way to simulate production level load without
- 6:08Speaker 2: touching your real development data.
- 6:10Speaker 1: That's smart.
- 6:11Speaker 2: And here's something that often surprises people. Post grescool has
- 6:14Speaker 2: transactional DDL.
- 6:15Speaker 1: Transactional DDL data definition.
- 6:18Speaker 2: Language like create table, exactly.
- 6:20Speaker 1: Schema changes, create index, alter table, ad column. They happen
- 6:24Speaker 1: inside a transaction just like data changes. So you can
- 6:28Speaker 1: literally type begin, then create index mix on my table call,
- 6:32Speaker 1: then realize you made a mistake and type roll back
- 6:34Speaker 1: and that index just poof never happened.
- 6:37Speaker 3: WHOA.
- 6:37Speaker 2: Okay, that's huge for safety. No half applied schema changes.
- 6:41Speaker 1: It's an incredible safety net. It means your migrations either
- 6:44Speaker 1: succeed completely or fail completely, which brings us back to
- 6:48Speaker 1: safe experimentation. Always test schema changes in staging first, and
- 6:53Speaker 1: maybe even use read only database users in production for
- 6:56Speaker 1: certain monitoring tasks. Using roles like p grade old data
- 6:59Speaker 1: or pgmont just adds another layer of safety.
- 7:02Speaker 2: Makes sense, Okay, let's switch gears a bit. Data correctness
- 7:05Speaker 2: data consistency obviously super important in rails. We often reach
- 7:08Speaker 2: for active record validations, but the force argues pretty strongly
- 7:11Speaker 2: for using database level constraints too. What's the thinking there?
- 7:14Speaker 2: Are they redundant not redundant complementary? That's the key. Active
- 7:19Speaker 2: record validations are great, essential, even for catching errors early
- 7:23Speaker 2: at the application layer, providing good user feedback. But database
- 7:27Speaker 2: constraints offer stronger guarantees because they're enforced inside the database engine,
- 7:33Speaker 2: which is built specifically to handle high concurrency transactions and
- 7:37Speaker 2: maintain data isolation in ways an application layer just can't.
- 7:41Speaker 1: Okay, stronger guarantees. What kind of constraints are we talking
- 7:44Speaker 1: about beyond say, primary key or.
- 7:46Speaker 3: Not in all, Oh, there's a whole suite.
- 7:48Speaker 2: You've got unique constraints obviously, foreign key constraints to maintain
- 7:51Speaker 2: relationships between tables, check constraints for custom rules, and even
- 7:55Speaker 2: more advanced exclusion constraints.
- 7:58Speaker 1: Let's take unique If I want to add one, but
- 8:00Speaker 1: I already have duplicate data, what do I do?
- 8:02Speaker 2: Good question? You typically need to clean up that data first,
- 8:06Speaker 2: the source mentions using a common table expression a CTE
- 8:09Speaker 2: with the row number window function. It's a neat trick
- 8:12Speaker 2: to identify and then delete the duplicates before you apply
- 8:15Speaker 2: the unique constraint.
- 8:16Speaker 1: Okay, and for and keys. Rails didn't always support those natively,
- 8:21Speaker 1: did it right?
- 8:21Speaker 2: Native support landed in rails four point two Before that
- 8:24Speaker 2: you use gems. But yeah, they're fundamental. They ensure, for example,
- 8:28Speaker 2: that you can't delete a rider if they still have
- 8:31Speaker 2: associated trips in the database. Prevents orphaned records.
- 8:34Speaker 1: Got it? What about che check constraints you said, custom rules, Yeah,
- 8:37Speaker 1: they're really flexible.
- 8:39Speaker 2: Anything that evaluates the true or false, like you could
- 8:41Speaker 2: enforce that a trips table's completed timestam must always be
- 8:44Speaker 2: later than it's create debt timestap. Simple powerful rule.
- 8:47Speaker 1: Okay, that makes sense, But this raises a practical point.
- 8:50Speaker 1: How do you add a cheat check constraint like that
- 8:52Speaker 1: to a table that's already huge and getting hammered with traffic.
- 8:55Speaker 1: Wouldn't that lock it up while it checks millions of
- 8:57Speaker 1: old rows?
- 8:58Speaker 2: Exactly the problem, and there's an elegant solution. You do
- 9:02Speaker 2: it in two spelps using rails migrations. First you add
- 9:06Speaker 2: check constraint, but pass the option validated false. This tells postgraschool, okay,
- 9:12Speaker 2: enforce this rule for all new or updated rows from
- 9:14Speaker 2: now on, but don't check the old ones yet. That
- 9:17Speaker 2: part is super fast.
- 9:18Speaker 1: Ah, so it doesn't block.
- 9:19Speaker 3: Right.
- 9:20Speaker 2: Then, in a separate later migration you run validated at
- 9:23Speaker 2: check constraint for that same constraint. This tells postgres school, okay,
- 9:27Speaker 2: now go back and check all the existing rows. But
- 9:30Speaker 2: it does so without taking such a heavy lock. It
- 9:32Speaker 2: avoids that downtime.
- 9:34Speaker 1: Clever two steps. What about deferring constraints?
- 9:37Speaker 2: Yeah, deferable Initially deferred. You can apply this to unique
- 9:41Speaker 2: primary key, foreign key, and exclusion constraints. It means the
- 9:45Speaker 2: constraint check is postponed until the very end of the transaction.
- 9:48Speaker 2: Super useful for things like say, reordering items in a
- 9:51Speaker 2: list where each item needs a unique position. You might
- 9:54Speaker 2: temporarily have duplicate positions during the transaction while you swap
- 9:57Speaker 2: things around, but as long as it's fixed by the
- 9:59Speaker 2: time you commit, it's okay.
- 10:00Speaker 1: Interesting, okay. You also mentioned exclusion constraints. Those sound advanced.
- 10:04Speaker 2: They are powerful and less common, but solve specific problems
- 10:07Speaker 2: really well. They prevent overlapping data across multiple roads in
- 10:11Speaker 2: the same table. The classic example is preventing overlapping time
- 10:15Speaker 2: ranges like booking a meeting room, or, in ride SHARE's case,
- 10:19Speaker 2: maybe preventing overlapping vehicle reservations. They usually require an extension
- 10:23Speaker 2: like beat read just and often use range types like
- 10:26Speaker 2: TSTs range for timestamp ranges along with the overlap operator
- 10:29Speaker 2: at datcha okay, quick detour case in sensitive unique emails
- 10:33Speaker 2: common problem. How does postgress will handle that?
- 10:36Speaker 3: Two main ways?
- 10:37Speaker 2: Really You could use the site text extension, which provides
- 10:40Speaker 2: a case in sensitive text type, or you can use generated.
- 10:43Speaker 1: Columns generated columns like virtual columns sorted.
- 10:46Speaker 2: Yeah, you define a column that's automatically computed based on others,
- 10:49Speaker 2: so you could have a lower mail generated column that
- 10:51Speaker 2: always stores lower email. Then you put a regular unique
- 10:54Speaker 2: index on that generated column. Rails actually supports these now too.
- 10:58Speaker 1: Neat and quickly. And domains right, create.
- 11:02Speaker 2: Type of gas as enom lets you define a fixed
- 11:05Speaker 2: list of a loudstring values for a column like trip statuses, pending, active, completed.
- 11:10Speaker 2: Create domain lets you create a custom data type based
- 11:13Speaker 2: on an existing one, but add check constraints to it,
- 11:16Speaker 2: making reusable validation rules both useful, different trade offs.
- 11:20Speaker 1: Okay, this is great for ensuring data integrity, but let's
- 11:23Speaker 1: talk about actually changing the database schema on a busy
- 11:26Speaker 1: production system. That moment when you run RAILSDB dot migrate,
- 11:30Speaker 1: it can be terrifying.
- 11:31Speaker 2: Oh yeah, the dreaded migration lock exactly.
- 11:34Speaker 1: Some alter table operations, they take what's called an access
- 11:37Speaker 1: exclusive lock, right, and that just blocks everything reads rights.
- 11:40Speaker 1: Your app grinds to a halt. How do we avoid
- 11:43Speaker 1: that absolute nightmare?
- 11:44Speaker 3: Right?
- 11:45Speaker 2: That exclusive lock is the enemy on a busy system.
- 11:47Speaker 2: The absolute key here, Your best friend really is the
- 11:50Speaker 2: concurrently keyword for operations like create index or drop index.
- 11:54Speaker 2: Adding concurrently tells postgress will to do the work without
- 11:57Speaker 2: taking that heavy lock. It takes longer, more resources, but
- 12:01Speaker 2: your application stays online.
- 12:02Speaker 3: It's a life saver.
- 12:03Speaker 1: So create index concurrently, drop index concurrently. Are there other
- 12:07Speaker 1: ways to stay safe?
- 12:08Speaker 3: Definitely.
- 12:09Speaker 2: There's a fantastic Ruby gym called strong Migrations. You add
- 12:12Speaker 2: it to your development environment and it actively watches your migrations.
- 12:16Speaker 2: If it spots a potentially dangerous operation, one that would
- 12:19Speaker 2: take an access exclusive lock and likely cause downtime, it'll
- 12:23Speaker 2: either warn you, suggest a safer multi step alternative like
- 12:27Speaker 2: the chi check constrained example, or even prevent the migration
- 12:30Speaker 2: from running in production by default.
- 12:32Speaker 1: Oh wow, So it enforces safer practices during development exactly.
- 12:36Speaker 2: It catches things early beyond that. You need safeguards at
- 12:39Speaker 2: the database level too, especially with high concurrency. Setting a
- 12:42Speaker 2: lock time out is crucial.
- 12:44Speaker 1: Lock time out that limits how long a query waits
- 12:46Speaker 1: for a lock.
- 12:47Speaker 2: Precisely, if a query can't get the lock it needs
- 12:50Speaker 2: within say, fifty milliseconds, it gets canceled instead of just
- 12:55Speaker 2: sitting there waiting indefinitely and potentially holding up other processes. Similarly,
- 12:59Speaker 2: stay time out puts a cap on how long any
- 13:02Speaker 2: single sequel statement is allowed to run, prevents runaway queries
- 13:05Speaker 2: from hogging resources. The source also mentions enabling log lock
- 13:09Speaker 2: weights and tuning deadlock timeout for better visibility in your
- 13:12Speaker 2: logs when contention happens. Okay, timeouts are key. What about
- 13:16Speaker 2: removing columns? I've heard that can cause weird errors too. Ah, yes,
- 13:20Speaker 2: so the stale schema cache problem. This happens when you
- 13:22Speaker 2: drop a column, but some of your running Rails application
- 13:25Speaker 2: servers haven't picked up the schema change yet, they try
- 13:27Speaker 2: to query the column that no longer exists.
- 13:29Speaker 3: Boom error.
- 13:31Speaker 1: Right, So how do you remove a column safely?
- 13:33Speaker 2: The recommended way is using active record dot base dot
- 13:36Speaker 2: ignored columns. It's a multi step process. First, you add
- 13:40Speaker 2: the column name to ignored columns in your Rails model,
- 13:43Speaker 2: deploy that code. Now rail simply pretends the column doesn't exist,
- 13:47Speaker 2: even though it's still in the database. Then, once your
- 13:50Speaker 2: sure no code is using it, you create and run
- 13:52Speaker 2: a migration to actually remove column. Finally, you remove the
- 13:55Speaker 2: column name from ignored columns in a later deploy. It's
- 13:58Speaker 2: gradual and safe.
- 14:00Speaker 1: Makes sense gradual removal. Now this brings up another big one.
- 14:04Speaker 1: What if you add a new column and need to
- 14:06Speaker 1: populate it for millions of existing rows backfilling data without downtime?
- 14:11Speaker 2: Yeah, that's a classic challenge. Running a massive up date
- 14:14Speaker 2: statement is usually out of the question. Too slow, too
- 14:17Speaker 2: much locking. You need online backfilling strategies. One approach is
- 14:20Speaker 2: double writing or dual rights. You modify your application code
- 14:24Speaker 2: to write to both the old location if any, and
- 14:26Speaker 2: the new column simultaneously. You run a background job to
- 14:29Speaker 2: backfill a new column for old records, and once it's done,
- 14:32Speaker 2: you switch weeds to the new column and eventually remove
- 14:34Speaker 2: the dual right logic and the old column.
- 14:36Speaker 1: Okay, double writing any other ways.
- 14:38Speaker 2: Another technique involves using intermediate tables. You create a temporary table,
- 14:42Speaker 2: maybe just with the primary key in the new column value.
- 14:45Speaker 2: You populate that table, perhaps marking it U and lodgy
- 14:48Speaker 2: so it doesn't hit replication, maybe disabling autovacuum on it
- 14:51Speaker 2: temporarily for speed. Then you batch update the main table
- 14:55Speaker 2: from this intermediate table. And crucially, all these backfilling processes
- 14:59Speaker 2: need to be done in small, manageable batches, often with
- 15:02Speaker 2: some kind of throttling or delay between batches to avoid
- 15:05Speaker 2: overwhelming the database or causing replication.
- 15:08Speaker 1: Lack batching and throttling. Got it, Okay, let's shift focus
- 15:12Speaker 1: to active record itself. It's amazing. Rails convention over configuration
- 15:16Speaker 1: is great, but yeah, it can sometimes generate pretty inefficient
- 15:20Speaker 1: queries if you're not paying attention right.
- 15:22Speaker 2: Absolutely, the abstraction is powerful, but it can hide what's
- 15:26Speaker 2: actually happening. So connecting this to the bigger picture, it's
- 15:29Speaker 2: about making your rails app smarter in how it communicates
- 15:32Speaker 2: with postgress.
- 15:32Speaker 1: How do we even spot the bad queries easily?
- 15:35Speaker 3: Well?
- 15:36Speaker 2: One really helpful thing in Roll seven and later is
- 15:38Speaker 2: the improved query logs. They can automatically add context like
- 15:42Speaker 2: which controller an action trigger the query right into the
- 15:45Speaker 2: sql log output. Makes tracing a slow query back to
- 15:48Speaker 2: your application code much much easier.
- 15:50Speaker 1: That sounds useful. What's a common inefficiency pattern?
- 15:53Speaker 3: Oh?
- 15:53Speaker 2: The absolute classic is the M plus one query problem?
- 15:55Speaker 2: You see it everywhere?
- 15:56Speaker 1: Ah, Yes, fetch one thing, then loop and fetch relate
- 16:00Speaker 1: things one.
- 16:01Speaker 2: By one exactly like load one hundred blog posts and
- 16:04Speaker 2: then inside the loop for each post, run another query
- 16:07Speaker 2: to get its author. That's one hundred and one database
- 16:09Speaker 2: queries when it could probably be just two kills performance.
- 16:13Speaker 1: Right, So how do we fix N plus one?
- 16:15Speaker 2: The primary solution is eager loading. You tell active Record
- 16:18Speaker 2: upfront what associated data you'll need, use methods like dot
- 16:22Speaker 2: preload or dot cludes rails, then cleverly figures out how
- 16:26Speaker 2: to load all that data in a minimal number of queries,
- 16:28Speaker 2: usually just one extra query for each association.
- 16:30Speaker 1: Yeah preload and dot includes.
- 16:32Speaker 2: Got it and a quick tip if you've already eagerloaded
- 16:35Speaker 2: data into an array of objects, use dot size to
- 16:38Speaker 2: get the count dot dot count. Dot size works unloaded
- 16:41Speaker 2: array in memory, dot count might trigger another database query
- 16:46Speaker 2: unnecessarily good tip.
- 16:47Speaker 1: Any other ways to prevent N plus one?
- 16:49Speaker 2: Yeah, Rail six point one introduce strict loading. You can
- 16:52Speaker 2: enable it per association or globally. If you try to
- 16:55Speaker 2: access an association that wasn't explicitly eger loaded, it raises
- 16:59Speaker 2: an error instead of silently running the en plus one query.
- 17:02Speaker 2: It forces you to be explicit and prevents the problem
- 17:04Speaker 2: by default.
- 17:05Speaker 1: Ooh, I like that force the good behavior. What about
- 17:07Speaker 1: optimizing individual queries?
- 17:09Speaker 2: Simple things First, always use limit If you don't need
- 17:11Speaker 2: all possible results, don't pull back ten thousand rows if
- 17:14Speaker 2: you only display twenty. Also, the returning clause on insert
- 17:18Speaker 2: active records dot insertle method supports this. Now it lets
- 17:21Speaker 2: you get back the IDs or other columns of the
- 17:23Speaker 2: rose you just inserted without needing a separate select query afterwards.
- 17:27Speaker 2: Saves a round trip.
- 17:28Speaker 1: Nice and processing large amounts of data use.
- 17:30Speaker 2: Active records batching methods dot finbach or dot in batches.
- 17:34Speaker 2: They retrieve records in batches default one thousand, which keeps
- 17:38Speaker 2: memory usage low and avoids overwhelming the database or your
- 17:41Speaker 2: application with enormous result sets. Much more reliable for large tables.
- 17:45Speaker 1: Okay, batching is key. What about more complex SQL logic?
- 17:48Speaker 1: Does Active record help there?
- 17:49Speaker 2: It does increasingly so. Active record has good support for subqueries.
- 17:54Speaker 2: Now you can construct queries where part of the ware clause,
- 17:57Speaker 2: for instance, is itself another SQL query, useful for things
- 18:01Speaker 2: like finding drivers who have completed more trips than the
- 18:03Speaker 2: overall average number of trips per driver.
- 18:05Speaker 1: Okay, subqueries. I've also heard about CT's common table expressions.
- 18:10Speaker 2: Yes, CTEs using the with keyword in SQL are fantastic
- 18:14Speaker 2: for complex queries. They'll let you break down a big,
- 18:17Speaker 2: hairy query into smaller named logical steps. It makes the
- 18:20Speaker 2: sequel vastly more readable and maintainable. Active record has ways
- 18:24Speaker 2: to build queries using CTEs.
- 18:25Speaker 1: Too, so better organization. What about views?
- 18:29Speaker 2: Database views are another way to encapsulate complex sequel. You
- 18:33Speaker 2: define the query logic as a view directly imposed cresscol
- 18:37Speaker 2: and then you can query it from rails, almost like
- 18:39Speaker 2: a regular table. The scenic gem is very popular for
- 18:43Speaker 2: managing database views within your rails migrations.
- 18:46Speaker 1: Okay, views and materialized views. What's the difference?
- 18:50Speaker 2: Ah, Now, this is where it gets really interesting. Materialized
- 18:52Speaker 2: views take it a step further. They don't just store
- 18:55Speaker 2: the query definition. They actually execute the query and store
- 18:59Speaker 2: the results physically like a cash table.
- 19:01Speaker 1: So queries against them are super fast.
- 19:03Speaker 2: Lightened fast because the complex calculation or joint is already done.
- 19:07Speaker 2: They're perfect for complex reports or dashboard data that doesn't
- 19:10Speaker 2: need to be absolutely real time.
- 19:12Speaker 3: And the cool part you.
- 19:13Speaker 2: Can often refresh them can currently update the stored data
- 19:16Speaker 2: without locking readers. Provided the materialized view as a unique
- 19:20Speaker 2: index defined on it, zero downtime updates for your cash data.
- 19:24Speaker 1: Wow, concurrent refresh that's powerful. What about caching within rails itself?
- 19:28Speaker 3: Right.
- 19:29Speaker 2: Rails has layers two. The query cash is automatic within
- 19:32Speaker 2: a single controller action. If you run the exact same
- 19:35Speaker 2: sequel query twice in one request, RAILS cash is the
- 19:39Speaker 2: result of the first call and returns it instantly the
- 19:41Speaker 2: second time, avoiding a redundant database.
- 19:44Speaker 1: Hit okay automatic per request.
- 19:45Speaker 2: Then there are prepared statements postcresscool can parse a query
- 19:49Speaker 2: plan once and reuse it for subsequent executions with different parameters.
- 19:54Speaker 2: RAILS uses these under the hood. Rail seven improved how
- 19:57Speaker 2: it handles them, making reuse more likely by numerrating columns,
- 20:00Speaker 2: which helps reduce parsing overhead.
- 20:02Speaker 1: And counter cases.
- 20:03Speaker 2: Counter cases are a common pattern, not strictly a RAILS feature,
- 20:06Speaker 2: but supported by it. You add an integer calumn to
- 20:09Speaker 2: a model, say trips count on the user model. Then
- 20:12Speaker 2: you can figure the trip model to automatically increment or
- 20:14Speaker 2: decrement that counter whenever a trip is created or destroyed
- 20:17Speaker 2: for that.
- 20:18Speaker 1: User, so you get counts almost instantly without a slow query.
- 20:21Speaker 2: Exactly reading the count is just reading it into your column.
- 20:25Speaker 2: The tradeoff is slightly increased right latency, you have to
- 20:27Speaker 2: update the counter, and potential for slight inconsistencies if things
- 20:31Speaker 2: go wrong but they're often a huge performance win for
- 20:34Speaker 2: frequently needed counts.
- 20:36Speaker 1: Makes sense. What about calculations like averages or sums.
- 20:39Speaker 2: Do them in the database. Don't pull a million numbers
- 20:42Speaker 2: back to Ruby just to calculate the average. Use CQL
- 20:45Speaker 2: aggregate functions like avg sum countet max min. Active record
- 20:50Speaker 2: provides methods like dot average sum, et cetera that generate
- 20:54Speaker 2: the correct sequel. It drastically reduces data transfer and Ruby
- 20:57Speaker 2: object allocation.
- 20:58Speaker 1: Right less object delocation is that a big deal?
- 21:00Speaker 2: It can be, especially in tight loops or high throughput scenarios.
- 21:04Speaker 2: Every active record object RAILS creates consumes memory and CPU cycles.
- 21:08Speaker 3: If you only need raw.
- 21:10Speaker 2: Data maybe for a report or an export, Using lower
- 21:12Speaker 2: level methods like dot find by Soukel or even active
- 21:15Speaker 2: record dot base, dot connection, dot execute can be significantly faster.
- 21:19Speaker 2: There were dren simpler data structures, hashes or rays instead
- 21:22Speaker 2: of full blown active record objects, dramatically reducing that allocation overhead.
- 21:26Speaker 1: Okay, lots of ways to optimize within RAILS, but let's
- 21:29Speaker 1: go deeper into the database itself. When a query hits postgriss, well,
- 21:33Speaker 1: how do we see what it's really doing? And how
- 21:36Speaker 1: do we choose the right index to speed it up.
- 21:38Speaker 2: Right now we're getting into database level observability. A really
- 21:42Speaker 2: crucial tool here is the pgstat statements extension we mentioned earlier.
- 21:46Speaker 2: You enable it in postcresq al dot COF.
- 21:48Speaker 1: What is it track?
- 21:49Speaker 2: It tracks execution statistics for every normalized query run against
- 21:53Speaker 2: your database, total time spent, average time, how many times
- 21:56Speaker 2: it was called, rose returned, et cetera. It's invaluable for
- 22:00Speaker 2: finding your most expensive queries globally, the ones consuming the
- 22:03Speaker 2: most database time overall, so you can.
- 22:05Speaker 1: See the biggest hitters across the whole application exactly.
- 22:08Speaker 2: It helps you prioritize optimization efforts for a more visual approach.
- 22:12Speaker 2: Pg hero is a great dashboard tool. Many teams use it.
- 22:15Speaker 2: It gives you a web UI to see slow queries.
- 22:17Speaker 2: It can analyze query plans using explain, show you large
- 22:20Speaker 2: tables indexes, find unused indexes, and even show currently running queries.
- 22:24Speaker 1: Pg Hero Okay, but the core tool is explain right.
- 22:28Speaker 3: Explain is fundamental running.
- 22:30Speaker 2: Explain before a query shows you post Grescol's plan for
- 22:33Speaker 2: executing it. Adding Analyze actually runs the query and shows
- 22:37Speaker 2: you the plan along with the actual time spent and
- 22:40Speaker 2: rose returned at.
- 22:40Speaker 1: Each step, so explain analyze gives you the real picture.
- 22:44Speaker 2: Yes, you can also add buffers to see memory usage
- 22:47Speaker 2: like cash hits and format YAMEL or JSON for easier parsing.
- 22:51Speaker 2: It shows you things like whether it's doing a sequential
- 22:53Speaker 2: scan reading the whole table usually bad, or an index
- 22:56Speaker 2: scan or ideally an index only scan. It shows estimated costs,
- 23:00Speaker 2: filter conditions. It's how you diagnose a slow query.
- 23:03Speaker 1: Which leads to the question how do you make sure
- 23:06Speaker 1: Postgress uses the index you think it should or figure
- 23:08Speaker 1: out if you're missing one.
- 23:09Speaker 2: Finding missing indexes often starts with looking for those slow
- 23:13Speaker 2: sequential scans and explain plans or MPG stats statements. Data
- 23:17Speaker 2: pg Hero also has a suggested indexes feature based on
- 23:20Speaker 2: its analysis the rail's best practices. Jim can sometimes flag
- 23:23Speaker 2: missing foreign key indexes too.
- 23:25Speaker 1: Can you make Postgress logs slow queries automatically YEP.
- 23:28Speaker 2: Set log minduration statement in postcressql dot com.
- 23:32Speaker 1: Yeah.
- 23:32Speaker 2: Any query taking longer than say, five or milliseconds gets
- 23:35Speaker 2: logged automatically. Even better, you can use the auto explain extension,
- 23:39Speaker 2: which automatically logs the explain plan for slow queries so
- 23:42Speaker 2: you see exactly why it was slow right in your logs.
- 23:45Speaker 1: Auto explain Nice. Okay, let's talk index type, single column,
- 23:48Speaker 1: multi column what's the strategy.
- 23:50Speaker 2: Well, a multi column index on ABC can be used
- 23:54Speaker 2: for queries filtering on A or A and B or A,
- 23:56Speaker 2: B and C, but generally won't be used efficiently if you.
- 23:59Speaker 3: Only filter on or C.
- 24:00Speaker 2: It's left to right. You need to think about your
- 24:02Speaker 2: query patterns. Sometimes multiple single column indexes are better. Sometimes
- 24:06Speaker 2: a carefully ordered multi column indexes key. You also want
- 24:09Speaker 2: to avoid redundant indexes, like having an index on A
- 24:12Speaker 2: and another on AB. The first one might be unnecessary.
- 24:14Speaker 1: Okay, what about indexing on like a lowercased email.
- 24:18Speaker 2: That's indexes on expressions. You can literally do create unique
- 24:21Speaker 2: index on users lower email. The index stores the result
- 24:25Speaker 2: of the lower function, allowing fast case in sensitive lookups
- 24:27Speaker 2: or uniqueness checks.
- 24:29Speaker 1: Cool now, GIM indexes those sound different.
- 24:32Speaker 3: Yeah.
- 24:32Speaker 2: GN stands for generalized inverted index and this is where
- 24:35Speaker 2: things get really interesting. For certain data types. GN indexes
- 24:39Speaker 2: are optimized for indexing columns that contain multiple values think
- 24:43Speaker 2: arrays or especially JSMB columns.
- 24:45Speaker 1: So you can efficiently query inside a JSMB.
- 24:47Speaker 2: Column exactly with a gene index on a json B
- 24:50Speaker 2: column holding, say, trip details, you could very quickly find
- 24:53Speaker 2: all trips where metadata bags and trunk is two, or
- 24:56Speaker 2: where metadata by water offered is true. Without a gen index,
- 25:01Speaker 2: searching inside json B is usually a slow, sequential scan.
- 25:05Speaker 2: Gn is also used by extensions like PGTRGM for fast
- 25:08Speaker 2: text similarity searches, finding Henry when someone types Henrietta, for example,
- 25:13Speaker 2: really powerful for fuzzy searching.
- 25:14Speaker 1: Wow, okay, jsonb's searching and fuzzy text. What are partial indexes?
- 25:18Speaker 2: Partial indexes are indexes that have a wear clause in
- 25:21Speaker 2: their definition. This means the index only includes rows that
- 25:24Speaker 2: match that wear clock.
- 25:25Speaker 1: Why would you too that to.
- 25:26Speaker 2: Make the index much smaller and more efficient. A classic
- 25:30Speaker 2: example is indexing soft deleted records. Create index on users
- 25:34Speaker 2: we're deleted at is not null. If only one percent
- 25:37Speaker 2: of your users are deleted, this index is tiny compared
- 25:39Speaker 2: to indexing all users. It's perfect for queries that specifically
- 25:43Speaker 2: target that subset of rows.
- 25:45Speaker 1: Smaller index faster queries for that subset, smart and brin indexes.
- 25:50Speaker 2: Brin block range index. Now, connecting this to the bigger picture,
- 25:53Speaker 2: think about very large tables may pen only tables like
- 25:57Speaker 2: event logs, where data is inserted in order off correlated
- 26:00Speaker 2: with the timestamp. Light created app for these tables. Britt
- 26:03Speaker 2: indexes can offer performance similar to a standard B tree
- 26:06Speaker 2: index for range queries like finding events between two timestamps,
- 26:10Speaker 2: but they're drastically smaller. We're talking maybe forty kilobytes versus
- 26:13Speaker 2: two hundred megabytes for the same data range.
- 26:15Speaker 1: It's huge space saving tiny indexes for ordered data. Interesting
- 26:19Speaker 1: do indexes help with order by? Why?
- 26:21Speaker 3: Absolutely?
- 26:22Speaker 2: If you have an index on the columns you're ordering by,
- 26:24Speaker 2: postgrescool can often just read the data directly from the
- 26:27Speaker 2: index in the correct order, avoiding a costly sorting step.
- 26:31Speaker 2: This includes handling a null's last or nulls first efficiently
- 26:34Speaker 2: if the index is.
- 26:35Speaker 1: Defined correctly, and covering indexes covering indexes.
- 26:38Speaker 2: This uses the inclue gag keyword added in post crescool eleven.
- 26:42Speaker 2: It lets you add extra columns to an index just
- 26:44Speaker 2: for their data, not for searching or ordering. The benefit
- 26:48Speaker 2: if a query can get all columns it needs both
- 26:50Speaker 2: for filtering, ordering and for the seleclist directly from the
- 26:53Speaker 2: index itself. Postgrescool can perform an index only scan. It
- 26:56Speaker 2: never even has to visit the main table heap that
- 26:58Speaker 2: avoids a whole layer of IO and can be a massive.
- 27:01Speaker 1: Performance boost index only scans got it. Okay, So we've
- 27:04Speaker 1: optimized queries, picked good indexes, but databases need ongoing care
- 27:09Speaker 1: right like cars needing oil changes. The source talks about vacuum, analyze,
- 27:13Speaker 1: re index the VR maintenance tasks.
- 27:15Speaker 2: Yeah, absolutely vital, and it loops back to how Postgres
- 27:18Speaker 2: school handles changes that NVCC system multiversion concurrency control. When
- 27:24Speaker 2: you update or delete a row, postgriss doesn't immediately overwrite
- 27:27Speaker 2: or remove the old data. It marks the old row
- 27:30Speaker 2: version as invisible to new transactions, but the physical space
- 27:34Speaker 2: isn't reclaimed right away. These invisible rows are called dead.
- 27:37Speaker 1: Toples, and those dead tuples are bloat exactly.
- 27:41Speaker 2: They take up space in your tables and indexes, making
- 27:43Speaker 2: them larger than they need to be, which can slow
- 27:45Speaker 2: down queries. This is where vacuum comes in.
- 27:48Speaker 1: So vacuum cleans up the dead tupules.
- 27:50Speaker 2: Yes, and the really neat thing is auto vacuum, which
- 27:53Speaker 2: is postgres schools built in background process that does this automatically.
- 27:57Speaker 2: It monitors tables for changes and runs vvace to reclaim
- 28:00Speaker 2: space and analyze an ed SHEBSI to update statistics for
- 28:04Speaker 2: the query planner periodically.
- 28:06Speaker 1: Be said, it's often too conservative.
- 28:07Speaker 2: Yeah, The default auto vacuum settings are often tuned for safety,
- 28:11Speaker 2: not aggressiveness. On busy databases with high right rates, lots
- 28:15Speaker 2: of updates and deletes, the default hittings might not keep
- 28:18Speaker 2: up and blow can accumulate. You can, and often should,
- 28:22Speaker 2: tune parameters like auto vacuum vacuum cost limit how much
- 28:25Speaker 2: work it does per run and vacuum vacuum cost delay
- 28:29Speaker 2: how long it pauses per tables or globally to make
- 28:33Speaker 2: it run more often or more aggressively to keep bloat
- 28:35Speaker 2: under control.
- 28:36Speaker 1: Okay, tune auto vacuum. What about indexes? Do they get
- 28:39Speaker 1: bloated to They do?
- 28:41Speaker 2: And indexes can become fragmented or inefficient over time for
- 28:44Speaker 2: rebuilding them. The best practice now is re index concurrently.
- 28:48Speaker 1: Ah concurrently again, so no downtime right.
- 28:51Speaker 2: Introduced in POSTGRESSCULL thirteen, it rebuilds the index in the
- 28:54Speaker 2: background without blocking reads or rights to the table. Once
- 28:57Speaker 2: the new index is ready, it swaps it in atomically.
- 29:00Speaker 2: For older Postgres versions, the Prakic extension can do something
- 29:03Speaker 2: similar for both tables and indexes.
- 29:05Speaker 1: So mostly rely on autovacuum and renex Concurrently, do you
- 29:08Speaker 1: ever need manual vacuum.
- 29:09Speaker 2: Sometimes you might run vacuum analyze your pable manually after
- 29:13Speaker 2: a huge data loaded deletion, just to make sure stats
- 29:16Speaker 2: are up to date immediately. There's also a vacuum ver
- 29:20Speaker 2: both option to see what it's doing, and since Postgres
- 29:23Speaker 2: twelve vacuum skip blocked is useful to make sure your
- 29:27Speaker 2: manual vacuum doesn't get stuck waiting for a lock on
- 29:29Speaker 2: the table.
- 29:30Speaker 1: Is there a way to see the bloat?
- 29:32Speaker 2: Yeah, you can actually simulate it locally for learning, disable
- 29:34Speaker 2: auto vacuum on a test table or on a ton
- 29:36Speaker 2: of you P dates and then use SQL queries you
- 29:38Speaker 2: can find them online or tools like pg hero to
- 29:41Speaker 2: estimate the table and index bloat. Then you could run
- 29:44Speaker 2: vaco full well, which does lock the table heavily, so
- 29:46Speaker 2: don't run it on production just to see it reclaim
- 29:48Speaker 2: the space aggressively. It helps build intuition.
- 29:51Speaker 1: Good for understanding. You mentioned unused indexes earlier.
- 29:54Speaker 2: Yes, crucial maintenance indexes aren't free, They take up disc
- 29:57Speaker 2: space and more importantly, they slow down rights insert update
- 30:01Speaker 2: to lead because the index has to be updated too regularly.
- 30:04Speaker 2: Identifying and removing unused or redundant overlapping indexes is a
- 30:08Speaker 2: key optimization. Tools like pg hero are great for finding
- 30:11Speaker 2: these based on usage statistics tracked by postcress, so.
- 30:14Speaker 1: Clean up unused indexes. How can we schedule these maintenance tasks?
- 30:18Speaker 2: The pupg chron extension is super handy for this. It's
- 30:21Speaker 2: a scheduler that runs inside postgress role itself. You can
- 30:24Speaker 2: use it to schedule recurring SQEL commands like running a
- 30:28Speaker 2: manual vacuum analyze on specific busy tables every night, or
- 30:31Speaker 2: maybe rebuilding certain indexes periodically with index.
- 30:35Speaker 1: Concurrently pgcra cron for scheduling any other quick maintenance tools.
- 30:39Speaker 2: The rails pg extras gem provides some convenient RAKE tasks
- 30:42Speaker 2: for common checks right from your railvapp, things like checking
- 30:46Speaker 2: database cash hit rates, finding long running queries, diagnosing lock contention,
- 30:51Speaker 2: and identifying null indexes. Null indexes yeah indexes where a
- 30:54Speaker 2: very high percentage of the entries are actually NLLL. Depending
- 30:57Speaker 2: on your queries, these might be candidates for conversion into
- 30:59Speaker 2: some more efficient partial indexes using a were column is
- 31:03Speaker 2: not NL class got.
- 31:05Speaker 1: It okay, final big area scaling, more users, more traffic.
- 31:09Speaker 1: This often leads to problems with database connections, right hitting limits.
- 31:13Speaker 2: Yeah, that's a common scaling bottleneck. Postgress will has a
- 31:16Speaker 2: hard limit on simultaneous connections set by the max connections parameter.
- 31:21Speaker 2: If your application tries to open more connections than that
- 31:24Speaker 2: limit allows, you get the dreaded fatal Sorry too many
- 31:28Speaker 2: clients already error?
- 31:29Speaker 1: Ugh yeah, not fun. How do you deal with that?
- 31:33Speaker 3: Well, first you need visibility.
- 31:34Speaker 2: Use pgstat activity again to see how many connections are open,
- 31:37Speaker 2: in what state they're in. Are they active, idle or
- 31:40Speaker 2: worryingly idle in transaction meaning a connection is holding a
- 31:43Speaker 2: transaction open but isn't doing any work. Potentially holding locks.
- 31:47Speaker 1: Idle in transaction is bad.
- 31:49Speaker 3: Very bad.
- 31:50Speaker 2: You need to find and fix the application code causing that.
- 31:53Speaker 2: But the main architectural solution for handling lots of connections
- 31:56Speaker 2: efficiently is connection pooling.
- 31:57Speaker 1: Connection pooling like pg bouncer.
- 32:00Speaker 3: It's exactly.
- 32:01Speaker 2: Pg bouncer is the standard, free, open source connection pooler
- 32:05Speaker 2: for Postgress. What's fascinating here is how it works. It
- 32:09Speaker 2: sits between your rails application and your postgrescool database. Your
- 32:12Speaker 2: Rails apps connect to pg bouncer, which can handle thousands
- 32:15Speaker 2: of front end connections, and pg bouncer maintains a smaller
- 32:19Speaker 2: managed pool of actual connections to the back end postgresscole database,
- 32:23Speaker 2: reusing them efficiently. It drastically reduces the overhead of constantly
- 32:27Speaker 2: opening and closing connections to Postgress itself.
- 32:30Speaker 1: So it lets you handle way more app servers without
- 32:32Speaker 1: overwhelming the database's connection limits.
- 32:34Speaker 2: Precisely, it's essential for scaling rails apps with postgresscool. You
- 32:38Speaker 2: do need to configure pg bouncer's pool modes though. Transaction
- 32:41Speaker 2: pooling is very common and efficient, but it has a catch.
- 32:44Speaker 2: It doesn't work well with postgrescool session based features like
- 32:47Speaker 2: prepared statements, so if you use transaction pooling, you generally
- 32:51Speaker 2: need to disable prepared statements in your rails database dot
- 32:54Speaker 2: eml oh.
- 32:55Speaker 1: Okay disable prepared statements for transaction pooling.
- 32:58Speaker 2: What's the alternative session pool mode in pg bouncer. It
- 33:01Speaker 2: works fine with prepared statements, but it's less efficient at
- 33:05Speaker 2: re using connections as it pins a back end connection
- 33:08Speaker 2: to a client for the entire session duration. It's often
- 33:11Speaker 2: the fallback if you can't disable prepared statements.
- 33:14Speaker 1: Got it? Transaction versus session pooling, and we still need
- 33:17Speaker 1: those timeouts right.
- 33:18Speaker 2: Absolutely, statement time out, lock, time out, and especially idle
- 33:22Speaker 2: in transaction. Session timeout become even more critical when you
- 33:26Speaker 2: have a pooler involved to prevent misbehaving application instances from
- 33:31Speaker 2: hogging pooled connections.
- 33:32Speaker 1: Okay, let's dive a bit deeper into locking. We mentioned
- 33:35Speaker 1: pessimistic locking.
- 33:37Speaker 2: Right postgressholes Default locks are taken up front. Peaglocks few
- 33:41Speaker 2: gives you the granular details you can explicitly request locks
- 33:44Speaker 2: in SQL. Select it for update is common. It locks
- 33:47Speaker 2: the rose you select, preventing any other transaction from updating
- 33:50Speaker 2: or deleting them or selecting them for update until your
- 33:52Speaker 2: transaction commits or rolls back.
- 33:54Speaker 1: What if the row is already locked.
- 33:55Speaker 2: By default for update will wait, but you can add
- 33:59Speaker 2: no weight If the row is locked, the query fails immediately,
- 34:03Speaker 2: or you can use skiplocked. This tells postgress to just
- 34:06Speaker 2: ignore any locked rows and return only the ones that
- 34:09Speaker 2: can lock immediately. Super useful for implementing job queues where
- 34:13Speaker 2: multiple workers might try to grab the next available job.
- 34:16Speaker 1: No wait and skip locked. Okay, is there a weaker.
- 34:19Speaker 2: Lock yees selectaseball for share. This takes a shared lock.
- 34:24Speaker 2: Multiple transactions can hold a shared lock on the same
- 34:26Speaker 2: row simultaneously. It prevents anyone from getting an exclusive lock,
- 34:30Speaker 2: like for update or from delete, but it allows other
- 34:33Speaker 2: transactions to also read or select for share. Useful if
- 34:36Speaker 2: you need to read data and ensure it doesn't change
- 34:37Speaker 2: before your transaction finishes, but you don't mind others reading
- 34:40Speaker 2: it too.
- 34:40Speaker 1: Okay, that's pessimistic locking and postgress. What about optimistic locking
- 34:44Speaker 1: and RAILS, right, that's different.
- 34:46Speaker 2: Active record optimistic locking is an application level strategy. You
- 34:50Speaker 2: add a lock version integer column to your table. When
- 34:53Speaker 2: railsloads a record, it remembers the lock version. When you
- 34:56Speaker 2: go to save it, RAILS checks if the lock version
- 34:59Speaker 2: in the database still match is the one it loaded.
- 35:01Speaker 2: If it doesn't match, meeting someone else modified the record
- 35:04Speaker 2: in the meantime, RAILS raises an active record stale object terror.
- 35:08Speaker 2: Instead of overwriting the changes, it forces you to handle
- 35:12Speaker 2: the conflict in your application code.
- 35:14Speaker 1: So detect conflicts at right time rather than preventing them
- 35:17Speaker 1: with locks exactly.
- 35:19Speaker 2: And then there are advisory locks. These are completely application
- 35:22Speaker 2: defined locks using functions like peak advisory lock key. They
- 35:26Speaker 2: don't lock table rows, they just lock an arbitrary number.
- 35:28Speaker 2: The key useful for coordinating background jobs or ensuring only
- 35:32Speaker 2: one process runs a specific task at a time without
- 35:35Speaker 2: needing a dedicated table.
- 35:36Speaker 1: Okay, lots of locking options shifting again. Dealing with large
- 35:40Speaker 1: data sets often means pagination. What are the pitfalls?
- 35:43Speaker 2: The biggest pitfall is traditional limit offset pagination. It's easy
- 35:47Speaker 2: to implement dot limit twenty dot offset, but it gets
- 35:51Speaker 2: incredibly slow on large tables as the offset value grows.
- 35:54Speaker 1: Why is high offset slow.
- 35:55Speaker 2: Because postgress will still has to fetch all the rows
- 35:58Speaker 2: up to the offset plus limit point, sort them, and
- 36:01Speaker 2: then discard the offset rows. So offset five hundred thousand
- 36:04Speaker 2: is going to be agonizingly slow because it has to
- 36:06Speaker 2: process over five million rows just to find the twenty
- 36:09Speaker 2: you want.
- 36:09Speaker 1: Ouch. So what's better for large tables? Cursors?
- 36:13Speaker 2: Database cursors declared cursor fetch solve the offset problem by
- 36:16Speaker 2: maintaining state on the server. They're consistent, but they have drawbacks.
- 36:21Speaker 2: They keep a transaction open, which consumes resources and doesn't
- 36:24Speaker 2: play well with pg bouncer's transaction pooling mode. An active
- 36:27Speaker 2: record doesn't natively support them easily.
- 36:29Speaker 1: Okay, So cursors are tricky, what's the recommended way?
- 36:32Speaker 2: Then key set pagination sometimes called seek based pagination. We
- 36:36Speaker 2: connect this to the bigger picture. This is generally the
- 36:38Speaker 2: most efficient method for large data sets. Instead of offset,
- 36:42Speaker 2: you use a wear clause based on the value of
- 36:44Speaker 2: the last item scene on the previous page, combined with
- 36:47Speaker 2: order buy and limit. For example, where is a last
- 36:50Speaker 2: seeded order by sp limit twenty. Because you're filtering directly
- 36:54Speaker 2: using an index column, the database can jump almost directly
- 36:57Speaker 2: to the starting point for the next page, avoiding scanning
- 37:00Speaker 2: all the previous rows. It stays fast even on page
- 37:02Speaker 2: ten thousand.
- 37:03Speaker 1: Key set pagination use the last scene value in the
- 37:06Speaker 1: wear clause, got it last topic Bulk data writes. How
- 37:10Speaker 1: to do those efficiently?
- 37:11Speaker 2: Upsorts are common, combining an insert with an update if
- 37:14Speaker 2: the row already exists. Postgrescoll has insert insert and tree
- 37:18Speaker 2: on conflict do nothing if it exists, ignore the insert
- 37:21Speaker 2: or insert in on conflict, do update set if exists,
- 37:23Speaker 2: update specify columns. Rails's insertal method has an on conflict
- 37:27Speaker 2: option to handle this, and Postcress fifteen introduced this standard
- 37:31Speaker 2: SQL merge command, which is even more powerful for complex
- 37:34Speaker 2: absurd logic.
- 37:35Speaker 1: Okay, upsurts handle conflicts. What about just loading lots of
- 37:37Speaker 1: new data like from a file.
- 37:39Speaker 2: For bulk loading from files, especially csvs, the absolute fastest
- 37:43Speaker 2: way is the native postgress will copy command copy mytable
- 37:46Speaker 2: from my fil dot csv with format csv header. It
- 37:50Speaker 2: bypasses a lot of the normal SQL processing overhead and
- 37:52Speaker 2: is incredibly efficient, especially if we run into the same
- 37:55Speaker 2: transaction as a create table or trunkate as it can
- 37:58Speaker 2: minimize wall loogging.
- 37:59Speaker 1: Then copy is king for bulk loads. Anything else cool
- 38:02Speaker 1: For external.
- 38:03Speaker 2: Data, yeah, this is a surprisingly powerful and clever tool
- 38:06Speaker 2: foreign data rappers, specifically the filep and do extension file
- 38:10Speaker 2: EPI darol lets you define an external file like CSV
- 38:14Speaker 2: log file as if it were a postcrescoll table. You
- 38:16Speaker 2: can then run SQL queries directly against that external file
- 38:19Speaker 2: without importing the data seriously.
- 38:21Speaker 1: Query as CSV file with SQL without loading it seriously.
- 38:24Speaker 2: Create extension fileffew year, create server file server foreign and
- 38:28Speaker 2: data wrapper FILEFEEDW, create foreign table, mylogues, server filesiver options,
- 38:33Speaker 2: fill namepath, dollars, dot csv, format csv. Then just selects
- 38:36Speaker 2: from milogues where air code e cools five hundred. It's
- 38:38Speaker 2: amazing for analyzing log files or accessing archive data stored
- 38:41Speaker 2: externally a real game changer sometimes.
- 38:44Speaker 1: Wow, Okay, what a journey we've been on. We started
- 38:48Speaker 1: right at the beginning, setting up that local performance lab
- 38:50Speaker 1: with rideshare. Then we dove into admin basics, safe experimentation,
- 38:55Speaker 1: then hit data integrity with constraints which go way beyond
- 38:58Speaker 1: basic rills validations. We tackled those scary production migrations, learning
- 39:02Speaker 1: about concurrently and tools like strong migrations. Then we really
- 39:05Speaker 1: got into optimizing active record itself n plus one queries,
- 39:08Speaker 1: eager loading cts, materialized views, and finally went deep into
- 39:13Speaker 1: postgress internals, explain advanced indexing like gins bren, partial indexes,
- 39:18Speaker 1: essential maintenance with vacuum and re index and handling scaling
- 39:21Speaker 1: challenges like connection pooling with pg bouncer locking, and efficient
- 39:24Speaker 1: folk data handling with copyy and even FDWs. You really
- 39:27Speaker 1: have gained a shortcut here to some seriously high performance
- 39:30Speaker 1: postgrescol skills. That's an incredibly valuable step.
- 39:33Speaker 2: It really is, and that's the goal, right to equip
- 39:35Speaker 2: you with these practical, actionable insights, hopefully some surprising facts
- 39:40Speaker 2: too that can genuinely make a difference in your applications.
- 39:43Speaker 2: You should now have a much deeper feel for how
- 39:46Speaker 2: postgresco operates and how to really harness its power with rails.
- 39:50Speaker 2: So maybe a final thought to leave you with, Given
- 39:53Speaker 2: all this immense power and flexibility we've uncovered in post
- 39:55Speaker 2: gris skool today, just think about your own work. Is
- 39:58Speaker 2: there existing application bottleneck, maybe something you struggled with that
- 40:02Speaker 2: could be dramatically simplified or sped up by using one
- 40:05Speaker 2: of these database features, maybe one you hadn't even considered before.
- 40:08Speaker 2: Keep asking that question, keep exploring, because continuously improving the
- 40:12Speaker 2: operational excellence of your databases, well, it's an ongoing process,
- 40:16Speaker 2: but it's definitely a rewarding one,