Latest / CyberCode Academy / Course 37 - Building Web Apps with Ruby On Rails | Episode 17:Mastering Versioning and Pagination
Transcript
- 0:00Speaker 1: Imagine you've built like a fundamentally brilliant application, I mean
- 0:04Speaker 1: the architecture of sound. The initial deployment went smoothly, and
- 0:07Speaker 1: you've actually found product market fit.
- 0:09Speaker 2: Right the dream scenario exactly the dream.
- 0:12Speaker 1: You are acquiring users rapidly, but then the metrics on
- 0:18Speaker 1: your dashboard start painting a very different picture.
- 0:21Speaker 2: Oh anywhere this is going.
- 0:22Speaker 1: Yeah, your database CPU utilization is just spiking to near
- 0:26Speaker 1: one hundred percent. The Ruby processes on your web servers
- 0:30Speaker 1: are bloating, They're consuming gigabytes of memory, and then they.
- 0:33Speaker 2: Just crash ouch. Yeah that hurts.
- 0:35Speaker 1: And simultaneously, your error tracking software is lighting up because
- 0:39Speaker 1: a segment of your users on legacy mobile clients are
- 0:42Speaker 1: suddenly throwing five hundred errors after recent database schema change.
- 0:46Speaker 2: Right, because you were in the middle of the classic
- 0:48Speaker 2: scaling trap. I mean, the systems you built to launch
- 0:51Speaker 2: the application are the exact systems currently suffocating it.
- 0:54Speaker 1: It's brutal, and that's exactly why we are dedicating this
- 0:57Speaker 1: deep dive to dismantling two of those major structural compromises.
- 1:02Speaker 2: Yeah, we really need to look at pagination and API
- 1:05Speaker 2: versioning today.
- 1:06Speaker 1: Right, and we are going to look at the mechanical
- 1:08Speaker 1: implementation of these concepts. You know, completely bypassing the surface
- 1:12Speaker 1: level definitions, we know what an API is. We know
- 1:15Speaker 1: that returning all projects on an unpaginated endpoint is essentially
- 1:18Speaker 1: a self inflicted denial of service attack.
- 1:21Speaker 2: Yeah, you're basically taking down your own app.
- 1:22Speaker 1: Okay, let's unpack this. We need to look at the
- 1:25Speaker 1: architectural consequences of how we chunk that data and well,
- 1:29Speaker 1: how we manage the life cycle of our API end
- 1:32Speaker 1: points when the underlying business logic inevitably changes.
- 1:36Speaker 2: Let's start with the sheer weight of the payload, right right.
- 1:39Speaker 2: When we talk about the cascading failure of an unpaginated endpoint,
- 1:43Speaker 2: the bottleneck usually originates at the database layer before it
- 1:46Speaker 2: ever even hits the network.
- 1:48Speaker 1: Oh really, not the network first, exactly.
- 1:50Speaker 2: I mean, if your client requests a list of ten
- 1:52Speaker 2: thousand projects, the database isn't just returning ten thousand rows.
- 1:56Speaker 2: If your serializers are rendering associated data like say the
- 2:00Speaker 2: author of the project or the tags attached to it,
- 2:03Speaker 2: and you haven't strictly eager loaded those associations while you
- 2:06Speaker 2: immediately trigger an N plus one query storm.
- 2:08Speaker 1: Oh wow, Yeah, that's like asking a librarian for a
- 2:11Speaker 1: book on history, and they respond by just dumping the
- 2:15Speaker 1: entire history section onto your desk.
- 2:17Speaker 2: This is a perfect analogy. And so the server is
- 2:20Speaker 2: executing ten thousand individuals sequel queries just to fetch the
- 2:25Speaker 2: authors for.
- 2:25Speaker 1: Those projects, which is insane.
- 2:27Speaker 2: It is. Then it attempts to load all ten thousand
- 2:31Speaker 2: active record objects into memory simultaneously.
- 2:34Speaker 1: So the Ruby garbage collector has to work overtime.
- 2:36Speaker 2: Yeah, and your response time drops from milliseconds to full seconds.
- 2:40Speaker 2: And then finally, the network layer is forced to push
- 2:43Speaker 2: a multi megabyte Jason payload down to a mobile client
- 2:46Speaker 2: that might be operating on a really weak three.
- 2:49Speaker 1: G connection, which is just going to punish the user,
- 2:51Speaker 1: I mean the memory pressure on the client side trying
- 2:53Speaker 1: to parse that Jason and render thousands of dom elements.
- 2:58Speaker 1: It will just cause the appt to freeze.
- 3:00Speaker 2: Exactly. So the standard mitigation is chunking the data using
- 3:03Speaker 2: offset based pagination.
- 3:05Speaker 1: Right, So you apply an order clause, a limit clause
- 3:07Speaker 1: to restrict the size of the payload, and an offset
- 3:09Speaker 1: clause to determine the starting point.
- 3:11Speaker 2: Yes, but relying on offset is a ticking time bomb
- 3:14Speaker 2: at scale.
- 3:15Speaker 1: Wait, really, let's drill into the mechanics of that time bomb,
- 3:18Speaker 1: because well, offset feels super intuitive on the surface.
- 3:22Speaker 2: It does feel intuitive, right, Like if.
- 3:23Speaker 1: You request page two with fifty items per page, the
- 3:28Speaker 1: database just uses offset fifty to skip the first fifty rows.
- 3:32Speaker 1: What's the problem?
- 3:33Speaker 2: The inefficiency lies in the execution plan. When a relational
- 3:37Speaker 2: database like postgres school receives an offset one hundred thousand command,
- 3:41Speaker 2: it doesn't just magically jump to row one hundred thousand
- 3:44Speaker 2: and one.
- 3:44Speaker 1: Wait it doesn't.
- 3:45Speaker 2: No, it physically scans, retrieves, and then discards the first
- 3:50Speaker 2: one hundred thousand rows before returning the next fifty.
- 3:53Speaker 1: Wow. Okay, that is wildly inefficient.
- 3:56Speaker 2: So as your users paginate deeper into the data set,
- 3:58Speaker 2: the database workload increases linearly. A query for page two
- 4:02Speaker 2: thousand is like significantly slower and more resource intensive than
- 4:06Speaker 2: a query for page two.
- 4:07Speaker 1: We see developers try to fix this by throwing indexing
- 4:10Speaker 1: at the problem.
- 4:10Speaker 2: Right all the time, But a standard B tree index
- 4:13Speaker 2: doesn't solve the underlying scan and discard behavior of offset.
- 4:16Speaker 2: You need a structural alternative.
- 4:18Speaker 1: Which is key set pagenation or what people usually call
- 4:21Speaker 1: cursor based pagination.
- 4:23Speaker 2: Exactly. Cursor pagenation fundamentally changes the SQEL query. Instead of
- 4:27Speaker 2: relying on offset, you leverage an indexed column, typically an
- 4:31Speaker 2: autoincrementing ID or a timestamp.
- 4:34Speaker 1: So the client sends a cursor, which is usually the
- 4:36Speaker 1: idea of the last item they received on the previous page.
- 4:39Speaker 2: Right, and then the database query simply becomes something like
- 4:42Speaker 2: where id is greater than the last scene ID limit
- 4:46Speaker 2: fifty oh.
- 4:47Speaker 1: I see, because the database is querying an indexed column
- 4:50Speaker 1: with a strict mathematical operator, it uses an index scan
- 4:54Speaker 1: to jump directly to that row in the B tree.
- 4:57Speaker 2: You got it. It completely bypasses the whole scan and disc
- 5:00Speaker 2: guard phase, so the.
- 5:01Speaker 1: Query performance remains totally flat like operating in a roughly
- 5:05Speaker 1: oh of one time complexity, regardless of whether you were
- 5:08Speaker 1: fetching the first page or the millionth page.
- 5:10Speaker 2: Yeah, which is huge for scaling, But you know, the
- 5:13Speaker 2: trade off with cursor pagenation is flexibility. You lose the
- 5:15Speaker 2: ability to jump directly to a specific page number. Right.
- 5:18Speaker 1: You can't just click go to page fifteen. You can
- 5:20Speaker 1: only navigate forward or backward relative to your.
- 5:23Speaker 2: Current position exactly. But for infinite scroll interfaces, which honestly
- 5:29Speaker 2: dominate modern mobile and web development. Cursor pagenation is really
- 5:32Speaker 2: the only mathematically sound approach at scale.
- 5:36Speaker 1: Okay, so let's talk about the implementation layer. In a
- 5:38Speaker 1: framework like Rails, the ecosystem is really heavily reliant on
- 5:43Speaker 1: pagination gems. Right, Specifically, things like will paginate or cuminari
- 5:48Speaker 1: very heavily reliant. Yeah, and I often look at my
- 5:50Speaker 1: gem file and question the need for these dependencies. I mean,
- 5:53Speaker 1: if pagenation ultimately boils down to just manipulating or wear
- 5:56Speaker 1: and limit clause on an active record relation, introduce a
- 6:00Speaker 1: sprawling library feels like unnecessary bloat.
- 6:03Speaker 2: I can understand that perspective.
- 6:04Speaker 1: Why shouldn't we just write a simple class or a
- 6:06Speaker 1: scope to handle this natively?
- 6:08Speaker 2: Well, if your only requirement is a raw unformatted data feed,
- 6:11Speaker 2: a custom scope is perfectly fine, but an API en
- 6:14Speaker 2: point rarely operates in complete isolation. True, Think about the
- 6:18Speaker 2: metadata your client needs to actually manage its own state.
- 6:21Speaker 2: The client needs to know if there is a next page,
- 6:23Speaker 2: a previous page, the total number of records, and the
- 6:25Speaker 2: total number of pages.
- 6:26Speaker 1: Right, and a robust pagination gems standardizes the generation of
- 6:30Speaker 1: all that metadata exactly, specifically injecting it into the HTTP
- 6:34Speaker 1: response headers.
- 6:35Speaker 2: Right, adhering to RC five nine eight eight. I mean
- 6:38Speaker 2: a good API shouldn't clutter the Jason payload itself with
- 6:41Speaker 2: pagination metadata. It should inject relational links into the link
- 6:45Speaker 2: HTTP header.
- 6:46Speaker 1: Oh that makes a lot of sense.
- 6:47Speaker 2: Yeah, And gem's like Comminary handle all the mathematical edge
- 6:51Speaker 2: cases of like out of bounds page requests. They standardize
- 6:54Speaker 2: the parameter parsing across fifty different controllers, and they automate
- 6:58Speaker 2: that header injection.
- 7:00Speaker 1: So building and maintaining that logic across a massive codebase
- 7:03Speaker 1: manually is just a significant drain on engineering resources exactly.
- 7:09Speaker 2: But those gems do introduce their own performance.
- 7:12Speaker 1: Traps right, specifically regarding the total pages calculation.
- 7:15Speaker 2: Yes, to tell the client how many total pages exist,
- 7:18Speaker 2: the GEM basically has to execute a count query across
- 7:21Speaker 2: the entire table ouch.
- 7:23Speaker 1: So if you have ten million records, that count query
- 7:25Speaker 1: can actually take longer than fetching the actual data chunk.
- 7:28Speaker 2: It absolutely can, which forces you into caching the total
- 7:32Speaker 2: count or will stripping out the total pages metadata entirely
- 7:36Speaker 2: for massive tables and just offering next or previous links.
- 7:40Speaker 1: Right, So the implementation details really matter because the tool
- 7:43Speaker 1: you choose dictates the hidden queries running on your database precisely. Okay,
- 7:48Speaker 1: so pagination solves the sheer weight of the data payload.
- 7:52Speaker 1: But what happens when the shape of that payload needs
- 7:54Speaker 1: to change. That's the next big hurdle, because an API
- 7:57Speaker 1: is basically a strict request response contract. When you initially launch,
- 8:01Speaker 1: that contract.
- 8:02Speaker 2: Is clean, beautifully clean.
- 8:03Speaker 1: But a year later, business requirements shift. You know you
- 8:07Speaker 1: need to rename database columns, merge data structures, or deprecate
- 8:11Speaker 1: old fields to optimize the serializers. You literally need to
- 8:14Speaker 1: rewrite the contract.
- 8:15Speaker 2: And the difficulty in rewriting that contract lies entirely in
- 8:19Speaker 2: the legacy clients. Right. If you have a web application,
- 8:21Speaker 2: you control the deployment. When you update the server, you
- 8:24Speaker 2: update the front end client simultaneously. Everyone is happy.
- 8:28Speaker 1: But mobile applications operate in a distributed, uncontrolled environment. I
- 8:33Speaker 1: mean a user might install your app, grant it permissions,
- 8:36Speaker 1: and then completely disable automatic updates.
- 8:39Speaker 2: Exactly, they are holding an old contract. So if your
- 8:42Speaker 2: server unilaterally changes the Jason structure, the parser on that
- 8:46Speaker 2: legacy mobile app just fails. The application crashes.
- 8:50Speaker 1: This is the mobile app dilemma. Yeah, I mean you
- 8:52Speaker 1: are effectively held hostage by users running two year old software.
- 8:57Speaker 2: It's terrifying, honestly.
- 8:59Speaker 1: To evolve the application without breaking backward compatibility, you have
- 9:03Speaker 1: to implement API versioning. We have to maintain the original
- 9:07Speaker 1: contract for the legacy users while offering the optimized contract
- 9:10Speaker 1: to the new clients.
- 9:11Speaker 2: Right, and the intuitive kind of naive approach is simply
- 9:14Speaker 2: put in the version number right in the URL path.
- 9:16Speaker 2: You maintain slash ap slash v one slash projects and
- 9:19Speaker 2: you build a new slash ap slash v two slash.
- 9:22Speaker 1: Projects, which is incredibly common.
- 9:24Speaker 2: URL version is common because it is explicit and easily debuggable.
- 9:27Speaker 2: You can look at the path and immediately know which
- 9:29Speaker 2: code path is being executed.
- 9:31Speaker 1: But from a strict rest architecture standpoint, it kind of
- 9:34Speaker 1: violates the core principle of resource identification, doesn't it.
- 9:37Speaker 2: It completely violates it. The URL should identify the resource itself,
- 9:42Speaker 2: the projects, not the specific representation of the resource.
- 9:46Speaker 1: Ah okay, So a cleaner architectural pattern is content negotiation.
- 9:50Speaker 2: Yes, what's fascinating here is how content negotiation handles this elegantly.
- 9:55Speaker 2: The URL remains singular slash appy slash projects. The version
- 10:00Speaker 2: negotiation occurs invisibly within the HTTP.
- 10:03Speaker 1: Headers, so when the client constructs the request, it passes
- 10:06Speaker 1: an accept header. Instead of just a generic application slash
- 10:10Speaker 1: JSON type, it sends a custom vendor MIME type exactly.
- 10:14Speaker 2: The structure typically looks like application slash VN do dot
- 10:17Speaker 2: mytracker dot v two plus json.
- 10:19Speaker 1: Right, So like applications slash VND dot mytracker dot v
- 10:23Speaker 1: two plus json.
- 10:24Speaker 2: You got it. The client is explicitly declaring, hey, I
- 10:27Speaker 2: want the project's resource, and I understand the version two
- 10:29Speaker 2: data structure. The server reads this header and routes the
- 10:32Speaker 2: request internally.
- 10:33Speaker 1: But if you implement this, you really have to address
- 10:35Speaker 1: the caching implications immediately. Oh absolutely, because if we use
- 10:38Speaker 1: the identical URL for both versions and rely solely on
- 10:41Speaker 1: the header, doesn't that compromise the caching layer?
- 10:44Speaker 2: It can.
- 10:44Speaker 1: Yeah, Like if a CDN is sitting in front of
- 10:46Speaker 1: the application, it uses the URL as the cash key.
- 10:50Speaker 1: So a modern client requests slash appy slash projects with
- 10:53Speaker 1: the v two header, the CDN fetches it from the
- 10:56Speaker 1: origin server and cashes the V two json right. Five
- 10:59Speaker 1: minutes later, a legacy client requests the exact same URL,
- 11:02Speaker 1: but with the V one header. The CDN sees a
- 11:05Speaker 1: URL match and solves the cashed V two Jason to
- 11:08Speaker 1: the legacy client, which instantly breaks the app.
- 11:10Speaker 2: This is the invisible landmine of content negotiation. To prevent
- 11:14Speaker 2: that cash collision, your server's HTTP response must include a
- 11:19Speaker 2: very header.
- 11:20Speaker 1: Ah Okay.
- 11:20Speaker 2: By returning very except, you are explicitly instructing the CDN,
- 11:24Speaker 2: or the browser cache or your reverse proxy to segment
- 11:27Speaker 2: its cash.
- 11:28Speaker 1: So the CDN will store a separate, distinct copy of
- 11:31Speaker 1: the response for every unique except header it receives for
- 11:34Speaker 1: that URL exactly.
- 11:35Speaker 2: It completely resolves the collision, but it does fragment your
- 11:38Speaker 2: cash pool, which can potentially lower your initial cash hit rates.
- 11:41Speaker 1: That's a huge trade off to keep in mind. Okay,
- 11:44Speaker 1: let's map out the mechanical routing of this in a
- 11:46Speaker 1: rails environment. Assuming we have handled the very header correctly,
- 11:51Speaker 1: we need to catch that custom mime type at the
- 11:53Speaker 1: front door. So we start in the configurates file.
- 11:56Speaker 2: Right, we implement routing constraints. Think of a routing constrained
- 11:59Speaker 2: class like an optical prism.
- 12:01Speaker 1: Oh I like that.
- 12:02Speaker 2: Yeah, you have a single beam of light coming in.
- 12:04Speaker 2: That's the incoming request URL. The constraint class acts as
- 12:07Speaker 2: the prism, inspecting the frequency of the request, which in
- 12:11Speaker 2: this case is the accept header.
- 12:13Speaker 1: Okay.
- 12:13Speaker 2: Inside the class, a matches method forces the string. If
- 12:16Speaker 2: the header specifies V two, the prism bends that request
- 12:20Speaker 2: down the V two routing path. If it detects V one,
- 12:23Speaker 2: it bends it down the V one path.
- 12:25Speaker 1: That is a great visualization. So we stack these constraints logically,
- 12:28Speaker 1: checking for the highest version first, and we absolutely must
- 12:31Speaker 1: include a fallbacker.
- 12:32Speaker 2: Always have a fallback.
- 12:33Speaker 1: The final constraint in the stack should be instantiated as
- 12:36Speaker 1: the default because if a request arrives with a malformed
- 12:39Speaker 1: header or like an entirely missing accept header, the default
- 12:42Speaker 1: constraint forces a match exactly.
- 12:45Speaker 2: It automatically routes the request to the most stable, legacy
- 12:49Speaker 2: version of the API. This ensures that poorly configured clients
- 12:52Speaker 2: don't just trigger fatal routing errors.
- 12:55Speaker 1: Right once the prism bends the request, it has to
- 12:57Speaker 1: hit a controller. Visualizing the filetree, we implement controller name spacing.
- 13:02Speaker 1: We construct an app controller's apv one directory and an
- 13:06Speaker 1: app controller's apv two directory. The request is physically isolated
- 13:10Speaker 1: into the correct codebase it is.
- 13:13Speaker 2: But this isolation immediately introduces the next big architectural headache,
- 13:17Speaker 2: severe code duplication.
- 13:19Speaker 1: Right because if our V two project's controller only exists
- 13:22Speaker 1: to change how one associated model is rendered in the
- 13:25Speaker 1: Jason response, we definitely do not want to copy and
- 13:27Speaker 1: paste the entire create, update index and destroy logic from
- 13:31Speaker 1: the V one controller. No.
- 13:32Speaker 2: Absolutely, not having.
- 13:33Speaker 1: Parallel codebases that are ninety percent identical is just a
- 13:36Speaker 1: maintenance nightmare. A bug fix in V one has to
- 13:39Speaker 1: be manually replicated in V two.
- 13:41Speaker 2: Yeah, you mitigate that duplication through controller inheritance and composition.
- 13:45Speaker 2: Your APIV two projects controller can actually inherit directly from
- 13:48Speaker 2: your APIV one project controller.
- 13:51Speaker 1: Oh, so you only override the specific actions, perhaps just
- 13:54Speaker 1: the show method that require the new behavior.
- 13:56Speaker 2: Exactly, or you know, moving further toward composition, and we
- 14:00Speaker 2: just extract the core business logic out of the controllers
- 14:04Speaker 2: entirely and place it into shared service objects.
- 14:07Speaker 1: So the controllers become incredibly thin routing layers.
- 14:11Speaker 2: Precisely, the V one and V two controllers both call
- 14:14Speaker 2: the same project creation service, but then they simply pass
- 14:17Speaker 2: the resulting object to entirely separate serialization templates.
- 14:21Speaker 1: Right, So inside your views directory you maintain isolated namespaces
- 14:25Speaker 1: for your Jason serializers. The V one j builder template
- 14:28Speaker 1: might map twenty different fields, while the V two template
- 14:31Speaker 1: is optimized to only return ten.
- 14:33Speaker 2: You've got it. The exact same database object is processed
- 14:36Speaker 2: by the exact same service layer, but it is serialized
- 14:39Speaker 2: into completely different contracts based entirely on the HTTP except hatter.
- 14:43Speaker 1: That is so clean, total backward compatibility is achieved without
- 14:46Speaker 1: sacrificing the maintainability of the core logic. Exactly well, we
- 14:50Speaker 1: have covered massive ground here. I mean, we took an
- 14:52Speaker 1: application that was collapsing under the weight of its own
- 14:54Speaker 1: data and implemented pagination.
- 14:56Speaker 2: We save the database.
- 14:58Speaker 1: We definitely did. We buy past the performance degradation of
- 15:02Speaker 1: offset scaling by utilizing keyset pagination where possible. We addressed
- 15:06Speaker 1: the generation of RFC compliant linkheaders using gems while you know,
- 15:11Speaker 1: being wary of that count query overhead. And then we
- 15:14Speaker 1: solved the payload shape problem. We insulated our legacy mobile
- 15:18Speaker 1: users through content negotiation, managing the very except header for
- 15:22Speaker 1: our CDN and structurally isolating our code based using routing
- 15:25Speaker 1: constraints and namespaced and herited controllers.
- 15:28Speaker 2: When you combine all these mechanisms, you really shift from
- 15:31Speaker 2: simply writing end points to engineering a resilient system.
- 15:35Speaker 1: Absolutely, but it is crucial to.
- 15:36Speaker 2: Recognize that the paradigms we just explored are entirely anchored
- 15:39Speaker 2: in REST conventions. In this model, the server is the
- 15:43Speaker 2: ultimate authority. The server defines the strict V one or
- 15:46Speaker 2: V two structure, and the client must just accept the
- 15:49Speaker 2: pre defined.
- 15:50Speaker 1: Payload, which introduces a major paradigm shift. When we look
- 15:53Speaker 1: at technologies like graphql. If the core problem of versioning
- 15:56Speaker 1: is that the server's pre defined contract changes, well, graph
- 16:00Speaker 1: quol flips the dynamic entirely. It gives the client the
- 16:03Speaker 1: power to construct the contract dynamically, requesting exactly the fields
- 16:07Speaker 1: it needs and nothing more.
- 16:09Speaker 2: Right, if an API is built effectively with a graph architecture,
- 16:13Speaker 2: strict versioning via except headers often becomes totally obsolete because
- 16:18Speaker 2: the client simply stops requesting deprecated fields.
- 16:21Speaker 1: The evolution of the client server contract is continuous, and
- 16:25Speaker 1: understanding the constraints of REST is what allows you to
- 16:28Speaker 1: understand the specific problems graphql was designed to solve. It
- 16:31Speaker 1: really is to cement the architecture we discussed today. I
- 16:34Speaker 1: have a practical mental exercise for you. The next time
- 16:37Speaker 1: you are assigned to build out a new endpoint or
- 16:39Speaker 1: update an existing feature, do not immediately open your editor.
- 16:43Speaker 2: Good advice.
- 16:44Speaker 1: Getch the data flow first. Map out the execution plan
- 16:47Speaker 1: for your pagination query like are you relying on an
- 16:50Speaker 1: index scan or are you forcing the database to process
- 16:53Speaker 1: a massive offset? Write down the exact string of the
- 16:56Speaker 1: custom mie type you will require the client to send. Finally,
- 17:00Speaker 1: diagram the inheritance tree of your controllers, ensuring you are
- 17:04Speaker 1: isolating the version logic without duplicating your service layer.
- 17:08Speaker 2: Visualizing the system at this level of granularity is really
- 17:11Speaker 2: what separates writing functional code from true software engineering, so true.
- 17:15Speaker 1: Thank you for joining us on this deep dive.