<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Imaan Mazreati on Medium]]></title>
        <description><![CDATA[Stories by Imaan Mazreati on Medium]]></description>
        <link>https://medium.com/@imaanmzr?source=rss-150b7de8cbc8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4mAtY2N738_mi5UUqXD7-w.jpeg</url>
            <title>Stories by Imaan Mazreati on Medium</title>
            <link>https://medium.com/@imaanmzr?source=rss-150b7de8cbc8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:19:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imaanmzr/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Postchi: A Self-Hosted API Client for Teams]]></title>
            <link>https://medium.com/@imaanmzr/postchi-a-self-hosted-api-client-for-teams-43f3ae6b6616?source=rss-150b7de8cbc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f3ae6b6616</guid>
            <dc:creator><![CDATA[Imaan Mazreati]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 09:40:52 GMT</pubDate>
            <atom:updated>2026-08-14T09:40:52.184Z</atom:updated>
            <content:encoded><![CDATA[<p>If your team lives in Postman or Bruno but you’d rather not ship API collections, environment secrets, and request history to someone else’s cloud, <strong>Postchi</strong> is worth a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-r01cF35i8CcudtgT_c3Q.png" /><figcaption>Postchi Api Client</figcaption></figure><p>It’s a multi-user, web-based API client you run on your own infrastructure. Same general workflow: build requests, organize collections, run tests. All without giving up control of your data.</p><h3>Why self-host?</h3><p>Most hosted API clients are convenient until they aren’t: vendor lock-in, per-seat pricing, secrets sitting on third-party servers, or compliance rules that say “keep this internal.”</p><p>Postchi is built for teams that want:</p><ul><li><strong>Your data stays yours.</strong> Collections, environments, and history live in your PostgreSQL database.</li><li><strong>Encrypted secrets.</strong> Environment variables marked as secrets are encrypted at rest (AES-256).</li><li><strong>No per-seat SaaS bill.</strong> Run it on a VM, homelab, or internal cluster.</li><li><strong>Real collaboration.</strong> Workspaces, roles, invites, and live editing over WebSocket.</li></ul><p>You get Postman-like ergonomics without the external dependency.</p><h3>What it does</h3><p><strong>Request builder.</strong> Full HTTP methods, params/headers/body/auth tabs, form-data with file uploads, GraphQL, variable interpolation ({{variable}}), and auth types from Basic to Bearer to API keys.</p><p><strong>Collections and environments.</strong> Organize requests in folders, scope variables at workspace/collection/environment level, and import from Postman, Bruno, OpenAPI, or cURL.</p><p><strong>Execution and testing.</strong> Send requests from the browser with timing breakdowns, write pre-request and test scripts (JavaScript), run whole collections with pass/fail reports, and save response examples.</p><p><strong>OpenAPI sync.</strong> Connect an OpenAPI 3 spec by URL and sync operations into collections, with a diff view when the spec changes.</p><p><strong>Team features.</strong> Role-based access (viewer, editor, owner), email invites, share links for read-only snapshots or one-click import, and an activity feed per workspace.</p><p><strong>Import and export.</strong> Postman v2.1 and Bruno in both directions. OpenAPI and OpenCollection on import.</p><h3>Self-hosting in practice</h3><p>Postchi ships as Docker Compose: PostgreSQL, Go API, Nuxt frontend, and Mailpit for local email during development.</p><pre>git clone https://github.com/imaanmzr/postchi.git<br>cd postchi<br>cp .env.example .env<br># set JWT_SECRET and ENCRYPTION_KEY (32 bytes each)<br>docker compose up --build</pre><p>Open http://localhost:3000, register the first user, and you&#39;re in. That account becomes the workspace owner.</p><p>For production, you mainly need three things configured in .env:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*g0RFj-9S5UdYCl0dm_KsZw.png" /></figure><p>Point SMTP at your mail server for team invites, put a reverse proxy in front for HTTPS, and you’re done. Migrations run automatically on API startup, and health/readiness endpoints (/health, /ready) are there for orchestrators.</p><p>You can also deploy as a <strong>single container</strong>: the Go backend can serve the built Nuxt static files when STATIC_FILES_PATH is set. One binary, one reverse proxy, one origin.</p><h3>Under the hood</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*NSg803CMB8wmVCdEPbVp7g.png" /></figure><p>MIT licensed. No telemetry, no account with us. Just your server, your Postgres, your team.</p><h3>Who is it for?</h3><p>Postchi fits internal platform teams, startups with compliance constraints, and anyone who already self-hosts Grafana, Gitea, or Vault and wants API tooling in the same spirit.</p><p>It’s not trying to replace every Postman Enterprise feature on day one (no SSO/OIDC yet, no mock servers; those are on the roadmap). But if you want a capable, team-ready API client that runs entirely on infrastructure you control, it’s a solid starting point.</p><p><strong>GitHub:</strong> <a href="https://github.com/imaanmzr/postchi">github.com/imaanmzr/postchi</a></p><p>Questions or feedback? Open an issue on GitHub. I’d love to hear how teams are using it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f3ae6b6616" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rethinking SOLID, Clean Code, and Modern Software Architecture]]></title>
            <link>https://medium.com/@imaanmzr/rethinking-solid-clean-code-and-modern-software-architecture-781a4ba46238?source=rss-150b7de8cbc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/781a4ba46238</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[vertical-slice]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Imaan Mazreati]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 11:54:04 GMT</pubDate>
            <atom:updated>2026-06-30T11:58:07.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ty1kuK5NmtJHTw2mQBA8Ug.png" /></figure><h3><strong>Rethinking SOLID, Clean Code, and Modern Software Architecture — What the Evidence Actually Says</strong></h3><h3>TL;DR</h3><p>SOLID and Clean Code are not laws of nature. They are habits that came out of a specific time: enterprise Java and C# development in the 2000s, when hardware was cheap and the main danger was messy, hard-to-change code, not slow code. Treating these habits as universal truth has filled a lot of codebases with interfaces, repositories, and service layers that exist for no real reason other than “that’s the pattern.” On top of that, what we now call “OOP” is not really what Alan Kay meant by the term. His version was about objects sending messages to each other, not the deep class hierarchies and dependency-injection containers we use today.</p><p>This article argues for a simpler default: write code that fits how the machine and the problem actually work, keep abstractions thin and earn their place, and stop treating Robert “Uncle Bob” Martin’s preferences as if they were engineering law.</p><p>Most of us learned to code inside one specific way of thinking: SOLID, taught like it was physics. Question it in an interview and people think you’re not a “real” senior engineer. But Casey Muratori’s benchmarks showed something people didn’t want to hear: code written in the “clean” style can run 10 to 60 times slower than plain, direct code, because interfaces and extra layers are not free. They break how the CPU cache works, stop the compiler from inlining functions, and confuse the CPU’s branch predictor. Mike Acton made an even bigger claim: OOP usually models the <em>problem</em> (a customer, a shape, a chair) instead of the <em>data’s real shape</em> in memory, and that’s backwards from how computers actually run.</p><p>This isn’t an argument for “no rules at all.” It’s an argument that we’ve been optimizing for the wrong thing, and that some of our most trusted patterns; the Repository, the pass-through Service layer, one interface per class; solved problems that good tooling has already solved for us. We just kept using them out of habit.</p><p>The same thing happens with the Repository pattern. It was built to hide raw, hand-written SQL in an age before good ORMs existed. Most teams kept using it long after EF Core, Dapper, and similar tools already did that job. So today, most repository layers are a thin, leaky wrapper around DbContext, adding an extra hop, an extra mock, and an extra interface, without removing any real complexity. Ayende Rahien, who built the RavenDB database for a living, has been making this point since 2009.</p><p>And the OOP most of us practice isn’t the OOP Alan Kay invented. He meant small objects sending messages to each other, not class hierarchies, not deep inheritance, not DI containers. That said, this specific point is more debated among programming historians than the “repository is often unnecessary” point, and this article treats it that way.</p><p>There is also real evidence on the other side: a 2024 controlled study found that SOLID-restructured code was actually <em>easier</em> to understand for working data scientists. So the real argument here is: don’t follow a pattern just because everyone does. Ask what it actually buys you, and what it actually costs. Most “best practices” never get asked that question with real numbers. This article tries to ask it.</p><h3>1. How an Engineering Habit Turned Into a Religion</h3><p>SOLID and Clean Code didn’t show up as universal law. They came from a specific situation: large enterprise Java and C# codebases in the 2000s, built by big teams over many years, where the biggest risk was <em>messy, uncontrolled change</em>, not slowness, not memory pressure. In that world, optimizing for “can ten people safely change this code without breaking each other’s work” made sense. Hardware was cheap compared to developer time, so that trade-off was reasonable.</p><p>The problem isn’t that these habits existed. The problem is that they got generalized way beyond their original context and turned into professional dogma instead of judgment you apply case by case. After Casey Muratori published his benchmarks, he said he got a flood of messages from developers who’d quietly suspected “clean” code was <em>less</em> maintainable too, not just slower but never felt safe saying it out loud. When his post hit Hacker News, it got 739 upvotes and 907 comments, one of the biggest programming threads that year. The argument split along a predictable line: people building long-lived, feature-heavy, I/O-bound systems said clean code optimizes for shipping fast, not for CPU speed, because most software spends most of its time waiting on something other than the CPU anyway. People building CPU-bound systems disagreed. Both groups were right for their own situation. The real disagreement was never about one snippet of code. It was about which constraint actually matters in your system, and almost nobody asks that question out loud before picking a pattern.</p><p>That’s the main failure this article is about: SOLID, Clean Code, and Repository aren’t <em>wrong</em>. They get applied without anyone asking what they cost <em>in this specific context</em>, because asking that question feels risky on a lot of teams.</p><h3>2. What Muratori Actually Measured</h3><p>Muratori used Robert Martin’s own example from the <em>Clean Code</em> book: a shape_base class hierarchy with virtual Area() methods for square, rectangle, triangle, and circle; and benchmarked it against less &quot;clean&quot; versions:</p><ul><li><strong>Baseline (clean, polymorphic):</strong> about 35 cycles per shape, going through the virtual function hierarchy.</li><li><strong>Switch statement instead of polymorphism</strong> (breaking the “prefer polymorphism over switch” rule): about 24 cycles per shape, 1.5x faster, just from removing the vtable lookup.</li><li><strong>A flat table, combining the data and the operation</strong> (also breaking “don’t expose internals”): about 3.0–3.5 cycles per shape, roughly 10x faster than the clean version.</li><li><strong>Adding a second property to each shape</strong> (to see if the gap shrinks as the code gets more realistic): the gap actually grew to about 15x, because the class-hierarchy version now pays the indirection cost twice.</li><li><strong>A lightly optimized SIMD (AVX) version:</strong> 20–25x faster than the original clean version, using none of the “clean” techniques at all.</li></ul><p>The reason isn’t vague, it’s mechanical. Virtual dispatch through a vtable stops the compiler from inlining the function, forces shapes to be stored as pointers (because they’re different sizes), breaks prefetching, and most importantly, hides a pattern across all four shapes (every area formula is some version of width × height) that the table-driven version could exploit. Muratori’s bigger point: “clean” code organizes by <em>type</em>, which hides operation-level patterns. Code organized by <em>operation</em> makes those patterns visible and fast.</p><p>Evan Teran ran the same benchmarks independently and made a sharper point: almost all of the slowdown comes from <em>virtual function dispatch specifically</em>, not from “clean code” as a whole philosophy. Teran isn’t anti-performance, he agrees virtual functions are a real trade-off, but he thinks “never expose internals” is stated too broadly. C++’s friend keyword exists exactly because letting two related classes see each other&#39;s internals is sometimes the right call, not something to ban outright.</p><p>This distinction matters. The strong, defensible version of the argument is: <em>virtual dispatch has a real, measurable performance cost, and that cost gets worse as your data model grows.</em> The weak, easy-to-attack version is: <em>“clean code” is bad.</em> Stick to the first one.</p><p><strong>What Robert Martin actually admitted.</strong> Muratori and Martin had a long public debate on GitHub after the post went viral. Martin didn’t dispute the numbers. His response was that nanosecond-level efficiency mattered more decades ago, and that modern CPUs are roughly 10,000x faster than the hardware he originally optimized by hand for. So for most software he listed web browsers and office apps, as opposed to compilers, game engines, or signal-processing code, trading CPU cycles for developer time is a reasonable default today. That’s a real, fair engineering position. But notice what it actually says: not “clean code makes software better,” but “clean code’s cost is usually affordable.” That’s a claim about trade-offs, not about quality in some absolute sense. For a fintech system or anything else with real latency requirements, the actual question is: which side of Martin’s own dividing line do your hot paths fall on? His framework doesn’t help you answer that, because it was never built to.</p><h3>3. Data-Oriented Design: A Different Way to Think</h3><p>Mike Acton’s 2014 CppCon talk, “Data-Oriented Design and C++,” makes the bigger argument behind Muratori’s numbers. Acton’s claim is blunt: transforming data is the only thing a program actually does. If you don’t understand your data, you don’t understand your problem. His issue with OOP specifically is that it organizes code around an <em>imagined model of the real world</em> (a Shape base class, a Customer entity, a PhysicsChair that inherits from Chair) instead of around how the data is actually shaped and used at runtime. Two chairs in the real world look alike. Two Chair objects in a game engine (one physics-driven, one static) may share almost nothing in how they&#39;re actually represented in memory, which makes a shared Chair base class a liability instead of a convenience.</p><p>Acton’s two core ideas, usable as a checklist for any project:</p><ol><li>You have to understand the data to understand the system. Design around the data’s real shape, not an idealized model of the problem.</li><li>There’s basically never just “one” of anything important. Design for the plural case (a batch of orders, a stream of events), because that’s what production actually looks like, not the singular case.</li></ol><p>This lens is useful well outside game engines. A payment pipeline built around PaymentService.Process(Payment p), as if the unit of work is always &quot;one payment&quot;, has the same mismatch Acton describes. In production, you never actually process just one payment under load.</p><h3>4. The Repository Pattern: A Closer Look</h3><h3>4.1 What it was originally for</h3><p>The Repository pattern, as defined in <em>Patterns of Enterprise Application Architecture</em>, was meant to hide the database access code from the rest of your application, useful back when “database access” meant raw, hand-written SQL or a thin, low-level data mapper. That was its actual job: isolate your domain code from messy, manual data access.</p><h3>4.2 Why it’s often pointless today</h3><p>Modern ORMs, EF Core, NHibernate, Dapper-with-mapping, and others, already give you that exact isolation. EF Core’s DbContext is not just a database connection wrapper. By design, it already behaves like both a Repository and a Unit of Work: DbSet&lt;T&gt; gives you an in-memory, queryable collection per entity (the Repository part), and DbContext.SaveChanges() tracks every change across all your entities and commits them together in one transaction (the Unit of Work part). This isn&#39;t an opinion, it&#39;s documented in EF Core&#39;s own source as the intended design.</p><p>So when a team puts a custom IOrderRepository on top of DbContext, they are not adding a new capability. They&#39;re wrapping an abstraction that is <em>already</em> an abstraction. You end up with an interface, a concrete implementation, a mock for tests, and an extra method call, all to do something DbContext was already doing for free underneath. Ayende Rahien, who has built and maintained ORMs professionally (he&#39;s the creator of RavenDB), has been pointing this out since 2009. His argument has two separate parts that show up differently in real codebases:</p><p><strong>The “too many methods, or too few” problem.</strong> A generic IRepository&lt;T&gt; (GetById, GetAll, Find(predicate)) works fine for the simplest cases. The moment your queries get even slightly complex, multiple optional filters, custom projections, specific fetch plans that generic interface can&#39;t express them without one of two bad outcomes: you either keep adding very specific methods (GetActiveCustomersByRegionWithOrders) until the interface is a mess, or you give up and expose IQueryable&lt;T&gt; directly; at which point you&#39;ve recreated DbContext, just with extra steps, and lost the one thing a repository was supposed to give you: a small, predictable contract.</p><p><strong>The “hidden performance tools” problem.</strong> In a later post, Ayende makes a sharper point: a repository layer hides the exact APIs you need to fix real performance problems controlling what gets fetched and when, batching multiple queries together, avoiding the N+1 query problem. He’s not against structure in general. His actual advice is: don’t add a repository (or even a service layer) for simple CRUD with no real business rules attached. Use the ORM directly. Save the abstraction for places where there’s actual logic worth hiding. An abstraction only earns its place when it’s hiding something that’s actually worth hiding.</p><h3>4.3 The hidden cost nobody talks about: new developers stop looking behind the curtain</h3><p>There’s a practical, day-to-day cost to this wrapping that doesn’t show up in benchmarks but shows up in real teams over time. Once a generic IOrderRepository.GetById(id) exists, new developers joining the project will just call it. They have no reason to look at what query EF Core actually generates, whether it&#39;s pulling in related entities they don&#39;t need, whether it&#39;s tracking changes when it doesn&#39;t have to, or whether it&#39;s running inside a transaction at all. The repository method <em>looks</em> simple, so it gets treated as simple. Six months later you have a dozen call sites quietly causing N+1 queries or loading entire object graphs for a read-only screen, and nobody noticed, because the abstraction was specifically built to stop people from having to think about what&#39;s happening underneath it. That&#39;s the opposite of what a good abstraction is supposed to do; a good abstraction hides <em>complexity</em>, not <em>the information you actually need to write correct code</em>. A thin wrapper that hides &quot;this calls DbContext.Orders.Where(...)&quot; isn&#39;t hiding complexity. It&#39;s hiding the one fact a developer needs to reason about performance and correctness.</p><p>Rob Conery makes a related point: combining Repository with Unit of Work mostly just re-implements what DbContext already does on its own (change tracking, a transaction boundary, query composition), so the &quot;abstraction&quot; is mostly duplicated surface area, not new capability. A separate critique of the <em>generic</em> repository specifically lands on the same conclusion from another angle: an interface that can only do CRUD can&#39;t express anything specific to your domain; which is the one thing that would have justified building it in the first place.</p><p>The usual counter-argument, “we might switch ORMs someday”, is the one Ayende and others note almost never actually happens in practice. And even when a switch does happen, a small, hand-written wrapper built at the moment you actually need it is usually cheaper than a generic abstraction maintained defensively for years against a migration that never comes.</p><h3>4.4 It depends on your architecture; and this is where I’ll give my own opinion</h3><p>Everything above is general advice, but whether the Repository pattern makes sense or not depends heavily on which architecture you’re using. This part is closer to my own opinion than a settled fact, though there are real sources that support it.</p><p>In <strong>Clean Architecture combined with Domain-Driven Design (DDD)</strong>, the Repository pattern usually isn’t optional, it’s part of the design. The Domain or Application layer is supposed to define repository interfaces so the domain logic never depends directly on EF Core, and the Infrastructure layer implements them. There’s a real, defensible reason for this in classic DDD: repositories there exist to enforce <em>aggregate boundaries</em> making sure you only ever load and save a whole aggregate as one consistent unit, not to hide the ORM. Even people who maintain popular Clean Architecture templates for .NET have explicitly said the repository pattern is the right choice when you’re doing DDD with real aggregate boundaries, and that this is a fundamentally different reason than “wrapping DbContext to allow swapping ORMs.&quot;</p><p>But here’s my opinion: in a <strong>microservices</strong> setup, that justification weakens a lot, and the layering itself becomes the problem. Clean Architecture organizes code by <em>technical role</em>, a Domain project, an Application project, an Infrastructure project, a Presentation project. A single feature (say, “cancel an order”) ends up with its pieces scattered across four different projects or folders, connected only by interfaces. In a microservice, which is already small and supposed to be a single cohesive thing, splitting it internally into these layers tears apart code that changes together for no benefit that matches the cost. You’re not protecting a large team from each other anymore, that’s already handled by the service boundary itself. You’re just adding internal walls inside a building that’s already a separate building. I think this is a case of applying monolith-era layering rules to a context where the original problem (a huge, shared codebase with many teams) doesn’t exist anymore, and the result is busywork: jumping through three files and two interfaces to understand one simple use case.</p><p>I believe there are sources that back this view up, and it does seem to be a fairly common complaint, not just my own: people who write about both architectures point out that Clean Architecture’s strict technical layering means code that changes together (a feature’s endpoint, its handler, and its database query) ends up scattered across separate projects, and that this gets worse, not better, as the system is split into smaller services, since each service now repeats the same internal scaffolding for a much smaller amount of actual logic. One critic put it more bluntly; re-adding heavy layered abstractions inside something that’s already isolated at the network boundary doesn’t add safety, it just adds ceremony, and teams that do it often haven’t actually engaged with their domain, they’re hiding behind structure instead of understanding the problem.</p><p><strong>Vertical Slice Architecture</strong> solves this specific problem, in my view, because it organizes code by <em>feature</em> instead of by <em>technical role</em>. Each feature, “cancel an order,” “create a payment”, lives in one folder with everything it needs: the endpoint, the request/response model, the handler, and the data access, all together. Nothing is scattered. One slice might use a small repository if it genuinely needs one; another slice might just call DbContext directly because the operation is simple CRUD with no logic to hide. The architecture doesn&#39;t force every feature to pay the same abstraction tax. This matches Acton&#39;s point from Section 3 too; code organized around what actually happens (a request, end to end) rather than around an idealized technical model tends to be both easier to follow and harder to get wrong.</p><p>To be fair to the other side: this isn’t a universally settled debate either. People who like Clean Architecture point out that VSA can lead to code duplication across slices if you’re not careful, and that VSA gives weaker guardrails for less experienced teams, since there’s no enforced structure stopping someone from putting business logic in the wrong place. The honest version of my opinion is: for a microservice with a small, focused scope, the cohesion VSA gives you is worth more than the guardrails Clean Architecture gives you. For a large, shared monolith with many teams and genuinely complex domain rules, Clean Architecture’s stricter separation might still earn its cost. Context decides this, not a universal rule which, ironically, is the whole point of this article.</p><h3>4.5 This is mostly a C#/.NET/Java thing</h3><p>One more thing worth naming directly: this entire debate, Repository vs. DbContext, Clean Architecture&#39;s four projects, &quot;where does this interface belong&quot;, barely exists in the same form in languages like Go or Python. In Go, a typical project is organized into packages and files inside one module. You don&#39;t usually split a single service into four separate compiled projects connected by interfaces just to enforce a dependency direction; you organize by package, and Go&#39;s interfaces are implicit and small by convention, so the kind of ceremony-heavy interface-per-class pattern common in C# doesn&#39;t really take hold the same way. Python is similar, modules and packages, not separate assemblies, and the dynamic type system makes a lot of the &quot;interface for swapping implementations&quot; reasoning less relevant in the first place, since duck typing already gives you most of that flexibility without declaring it up front.</p><p>A lot of this isn’t really about software architecture in the abstract, it’s downstream of what .NET and Java’s tooling and project systems make easy. A solution full of separate class library projects, each compiled to its own DLL, with strict reference rules enforced by the build system, naturally pulls people toward this kind of heavy technical layering, because the tooling rewards it (clean dependency graphs, clear project boundaries, enforced compile-time rules). Go and Python don’t have that same project-level ceremony, so the equivalent debates over there tend to be about package boundaries and module structure instead of “which of four layers does this interface belong in.”</p><h3>5. Service Layers and Too Many Interfaces</h3><p>The repository problem generalizes. The same failure pattern shows up in service layers, “one interface per class” conventions, and DI containers loaded with interfaces: an abstraction gets added <em>just in case it’s needed later</em>, not because it’s solving a problem that exists right now.</p><p>A useful, concrete test: does this interface have more than one real implementation, or is it standing in for a variation that doesn’t actually exist yet? An IPaymentGateway interface with two genuinely different implementations (a sandbox gateway and a production one, or two different payment processors) is doing real work, it&#39;s hiding a real difference. An IOrderRepository interface with exactly one implementation, added purely &quot;for testability,&quot; is doing something else entirely, it&#39;s substituting indirection for a decision that was never actually in question. Interfaces should track real variation, not serve as default ceremony applied to every class regardless of whether anything actually varies.</p><p>This matters even more in microservices, which changes the math from the monolith-era thinking that produced SOLID and Repository in the first place. A service boundary is <em>already</em> an abstraction layer. It already isolates implementation details, already allows independent deployment and internal refactoring, and already gives you the substitutability that an internal interface-per-class convention was trying to fake inside a single process. Adding heavy internal abstraction layers <em>inside</em> a service that’s already isolated at the network boundary is abstracting the same problem twice and the second layer rarely earns its cost the way the first one did.</p><h3>6. What OOP Actually Was, vs. What We Built</h3><p>This part deserves more care than the performance section, because the history here is genuinely debated among people who’ve studied it closely not just between Muratori and Martin.</p><p>The popular version of the story: in a 2003 email to Stefan Ram, Alan Kay said that to him, object-oriented programming meant only three things: messaging, local state retention, and extreme late-binding, and explicitly <em>not</em> the class hierarchies, inheritance, and subclass polymorphism that dominate Java, C#, and most enterprise OOP today. Eric Elliott’s widely shared piece builds on this: early Smalltalk’s central idea was small, encapsulated objects communicating purely through messages (loosely modeled on biological cells or independent networked computers) specifically to avoid the split between data structures and the procedures that act on them.</p><p>The complicating evidence: software historian Hillel Wayne has argued that the “messaging is everything, classes were always secondary” story is actually a later retrofit. Kay’s own 1972 Smalltalk manual describes classes as the <em>central</em> mechanism for how objects communicate, not an afterthought. Simula, which directly inspired Kay, already combined objects, classes, and message-style communication as one package, and the 1981 <em>Byte</em> magazine issue that popularized both Smalltalk and the term “object-oriented” credits Simula with originating objects, messages, and classes together, as one idea. Kay himself, in a 1998 mailing-list post, said he regretted coining the term “objects” partly because it pulled attention away from messaging, but that’s a regret expressed decades later, not evidence that messaging was understood as the main idea at the time.</p><p>So the version of this argument that actually holds up is narrower than “Kay’s OOP never had classes.” It’s that Kay, in his own later and repeated framing, did not consider inheritance and subclass polymorphism essential to what he meant by object orientation, and that’s a real, citable disagreement with how the term gets used in mainstream class-based languages today. Whether messaging was <em>always</em> understood as the main mechanism, even in the earliest Smalltalk systems, is a more genuinely open question than the confident “Kay’s true vision was messaging” story usually suggests.</p><p>There’s also a likely structural reason the industry standardized on class-based, statically-typed OOP instead of Kay’s more dynamic model: tooling. Java and C#’s static structure made autocomplete, static analysis, and automated refactoring possible in ways Smalltalk’s late-bound dynamism actively resisted. IDE tooling requirements (not a considered rejection of Kay’s ideas) probably did a lot of the actual selecting here.</p><h3>7. Where the Evidence Doesn’t Support This Article’s Thesis</h3><p>A 2024 controlled study (Cabral et al., presented at the IEEE/ACM CAIN conference) tested whether applying SOLID actually improves code understanding, using real industrial machine-learning code and 100 data-scientist participants, split into a SOLID-restructured group and a control group. Result: applying SOLID produced a statistically significant improvement in how well people understood the code, especially for the Interface Segregation and Open-Closed principles, and the effect was strongest among professional data scientists at a large IT company.</p><p>This doesn’t rescue the dogma, exactly, the study measures <em>comprehension by people unfamiliar with the codebase</em>, on relatively small ML pipeline code, not long-term maintainability, not performance, and not whether the same benefit holds in large, evolved enterprise systems with real query complexity. But it’s real, peer-reviewed, controlled evidence that SOLID’s stated benefit, easier-to-understand code, does show up empirically, at least in this setting. The honest takeaway isn’t “SOLID is good” or “SOLID is bad.” It’s that the cost (Muratori’s world: tight, performance-critical code) and the benefit (Cabral et al.’s world: newcomers reading small, well-scoped modules) were measured in completely different contexts, and the dogma problem is treating either result as if it generalizes to all software, when neither study actually claims that.</p><h3>8. A Practical Alternative</h3><p>None of this is an argument for zero structure. It’s an argument for making abstraction answer to evidence instead of habit:</p><ul><li><strong>Profile before you architect for performance.</strong> Muratori’s numbers apply to tight, hot-path computation. Most enterprise code is I/O-bound. The first question is which kind of code you’re actually writing, not “are abstractions bad.”</li><li><strong>Let interfaces track real variation, not hypothetical future variation.</strong> One implementation, no concrete plan for a second, that interface is ceremony.</li><li><strong>Treat the ORM as already-abstracted.</strong> A repository layer should only exist where it adds something the ORM doesn’t already give you, a real, meaningful query contract, not a passthrough.</li><li><strong>Save service-layer abstraction for actual business logic.</strong> Simple CRUD with no rules attached doesn’t need a service wrapping a repository wrapping a DbContext.</li><li><strong>In microservices, let the service boundary do the isolation work it’s already doing</strong>, instead of re-implementing the same isolation again inside it with interfaces and DI containers.</li><li><strong>For genuinely hot paths</strong>, payment loops, matching engines, anything processing batches under load, borrow Acton’s lens: design around the data’s real shape in production (plural, batched, concrete), not an idealized one-object-at-a-time model.</li><li><strong>Pick your layering style to match your scope.</strong> Clean Architecture’s strict technical layers make more sense for a large, shared codebase with genuinely complex domain rules. Vertical Slice Architecture’s feature-first cohesion tends to fit a small, focused microservice better, fewer scattered files for the same amount of logic, and abstraction added only where a given feature actually needs it.</li></ul><h3>Sources</h3><ol><li>Casey Muratori, <a href="https://www.computerenhance.com/p/clean-code-horrible-performance">“Clean” Code, Horrible Performance</a> — Computer, Enhance!, Feb 2023. Source for all benchmark numbers in Section 2.</li><li><a href="https://se-radio.net/2023/08/se-radio-577-casey-muratori-on-clean-code-horrible-performance/">SE Radio 577: Casey Muratori on Clean Code, Horrible Performance</a> — Aug 2023.</li><li>Robert C. Martin &amp; Casey Muratori, <a href="https://github.com/unclebob/cmuratori-discussion/blob/main/cleancodeqa.md">public GitHub debate</a>.</li><li>Evan Teran, <a href="https://blog.codef00.com/2023/04/13/casey-muratori-is-wrong-about-clean-code">Casey Muratori is Wrong About Clean Code (But He’s Also Right)</a> — 2023.</li><li><a href="https://thenewstack.io/when-clean-code-hampers-application-performance/">When ‘Clean Code’ Hampers Application Performance</a> — The New Stack, Apr 2023.</li><li><a href="https://news.ycombinator.com/item?id=34966137">“Clean” code, horrible performance — Hacker News discussion</a> — Mar 2023.</li><li>Mike Acton, <a href="https://www.youtube.com/watch?v=rX0ItVEVjHc">Data-Oriented Design and C++</a> — CppCon 2014.</li><li>Ayende Rahien, <a href="https://ayende.com/blog/3955/repository-is-the-new-singleton">Repository is the new Singleton</a> — Apr 2009.</li><li>Ayende Rahien, <a href="https://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer">Architecting in the pit of doom: The evils of the repository abstraction layer</a> — 2011.</li><li>Rob Conery, discussed in <a href="https://www.thereformedprogrammer.net/is-the-repository-pattern-useful-with-entity-framework-core/">Is the Repository Pattern Useful With Entity Framework Core?</a> — The Reformed Programmer.</li><li><a href="https://www.infoworld.com/article/2248622/design-patterns-that-i-often-avoid-repository-pattern.html">Design Patterns That I Often Avoid: Repository Pattern</a> — InfoWorld.</li><li>Alan Kay, email to Stefan Ram, Jul 2003.</li><li>Eric Elliott, <a href="https://medium.com/javascript-scene/the-forgotten-history-of-oop-88d71b9b2d9f">The Forgotten History of OOP</a>.</li><li>Hillel Wayne, <a href="https://www.hillelwayne.com/post/alan-kay/">Alan Kay Did Not Invent Objects</a> — 2019.</li><li>Raphael Cabral et al., <a href="https://arxiv.org/pdf/2402.05337">Investigating the Impact of SOLID Design Principles on Machine Learning Code Understanding</a> — CAIN 2024.</li><li><a href="https://threedots.tech/episode/is-clean-architecture-overengineering/">Is Clean Architecture Overengineering?</a> — Three Dots Labs. Source for the “context switching across layers” and “every technique should help you ship faster, not slower” arguments in Section 4.4.</li><li><a href="https://github.com/jasontaylordev/CleanArchitecture/discussions/482">“This is not exactly The Clean Architecture style” — GitHub discussion on jasontaylordev/CleanArchitecture</a>. Source for “the repository pattern is the right choice for DDD with aggregate boundaries — a different motivation than wrapping DbContext” in Section 4.4.</li><li><a href="https://ricofritzsche.me/why-vertical-slices-wont-evolve-from-clean-architecture/">Why Vertical Slices Won’t Evolve from Clean Architecture</a>. Source for the “abstraction hiding behind layers nobody actually needs” critique referenced in Section 4.4.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=781a4ba46238" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimistic Locking in .NET]]></title>
            <link>https://medium.com/@imaanmzr/optimistic-locking-in-net-bd677916ef60?source=rss-150b7de8cbc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd677916ef60</guid>
            <category><![CDATA[optimistic-locking]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Imaan Mazreati]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 16:27:07 GMT</pubDate>
            <atom:updated>2024-11-03T16:27:07.594Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimistic Locking in .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZKtg85fKUf-tchBENt44eQ.png" /></figure><p>Optimistic locking in Entity Framework Core (EF Core) helps manage concurrency by detecting conflicts when updating data rather than preventing them upfront. This is typically done using a RowVersion or a Timestamp column, which helps ensure that the data being updated hasn’t changed since it was last read. Below are various examples of implementing optimistic locking in EF Core.</p><h3>1. Using a RowVersion/Timestamp Property</h3><p>The most common way to implement optimistic concurrency control in EF Core is using a RowVersion or Timestamp column in the database. This column gets updated automatically when a record is updated.</p><h4>Example Entity with RowVersion</h4><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br>    public string Name { get; set; }<br>    public int Quantity { get; set; }<br><br>    // RowVersion property to handle concurrency<br>    [Timestamp]<br>    public byte[] RowVersion { get; set; }<br>}</pre><ul><li>The [Timestamp] attribute is used to configure the RowVersion property, making it a concurrency token.</li><li>EF Core will include the RowVersion property in the WHERE clause of UPDATE statements to ensure the record hasn&#39;t been modified since it was last read.</li></ul><h4>Example Update with Optimistic Locking</h4><pre>try<br>{<br>    using (var context = new YourDbContext())<br>    {<br>        var productId = 1;<br>        var product = context.Products.Single(p =&gt; p.ProductId == productId);<br><br>        // Modify the product.<br>        product.Quantity -= 5;<br><br>        // Save changes with optimistic concurrency control.<br>        context.SaveChanges();<br>    }<br>}<br>catch (DbUpdateConcurrencyException ex)<br>{<br>    // Handle the concurrency exception, such as by informing the user or retrying the operation.<br>    Console.WriteLine(&quot;The data was updated by another transaction.&quot;);<br>}</pre><ul><li><strong>DbUpdateConcurrencyException</strong>: This exception is thrown when EF Core detects that the RowVersion has changed since the data was initially read.</li><li>The application can handle the exception, such as by retrying the update or informing the user about the conflict.</li></ul><h3>2. Using a ConcurrencyCheck Attribute</h3><p>Another way to implement optimistic concurrency is to use the [ConcurrencyCheck] attribute on one or more properties. This attribute ensures that EF Core checks for changes in those properties before updating the record.</p><h4>Example Entity with ConcurrencyCheck</h4><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br>    public string Name { get; set; }<br><br>    // This property will be checked for concurrency conflicts.<br>    [ConcurrencyCheck]<br>    public int Quantity { get; set; }<br>}</pre><ul><li>In this example, the Quantity property is marked with [ConcurrencyCheck], so EF Core includes it in the WHERE clause during updates.</li></ul><h4>Example Update with ConcurrencyCheck</h4><pre>try<br>{<br>    using (var context = new YourDbContext())<br>    {<br>        var productId = 1;<br>        var product = context.Products.Single(p =&gt; p.ProductId == productId);<br><br>        // Modify the product.<br>        product.Quantity -= 5;<br><br>        // Save changes with concurrency control.<br>        context.SaveChanges();<br>    }<br>}<br>catch (DbUpdateConcurrencyException ex)<br>{<br>    // Handle concurrency exception.<br>    Console.WriteLine(&quot;Concurrency conflict occurred. The data was changed by another transaction.&quot;);<br>}</pre><ul><li>This method is less precise than using a RowVersion, as it only checks the Quantity field rather than the entire entity for changes.</li></ul><h3>3. Handling Concurrency Conflicts with Custom Logic</h3><p>When handling a DbUpdateConcurrencyException, you might want to resolve the conflict by either retrying the operation, discarding changes, or merging the updates. Here’s an example of handling conflicts with custom logic:</p><pre>try<br>{<br>    using (var context = new YourDbContext())<br>    {<br>        var productId = 1;<br>        var product = context.Products.Single(p =&gt; p.ProductId == productId);<br><br>        // Modify the product.<br>        product.Quantity -= 5;<br><br>        context.SaveChanges();<br>    }<br>}<br>catch (DbUpdateConcurrencyException ex)<br>{<br>    var entry = ex.Entries.Single();<br>    var databaseValues = entry.GetDatabaseValues();<br><br>    if (databaseValues == null)<br>    {<br>        Console.WriteLine(&quot;The record was deleted by another user.&quot;);<br>    }<br>    else<br>    {<br>        var databaseProduct = (Product)databaseValues.ToObject();<br><br>        // Example of resolving conflict by setting database values.<br>        entry.OriginalValues.SetValues(databaseValues);<br><br>        // Optionally, retry the operation after resolving the conflict.<br>        context.SaveChanges();<br>    }<br>}</pre><ul><li><strong>GetDatabaseValues()</strong>: Retrieves the values from the database to see what has changed.</li><li>This example shows how to compare the in-memory entity with the database values and decide how to resolve the conflict (e.g., retrying, keeping the database values).</li></ul><h3>4. Using Fluent API for Concurrency Tokens</h3><p>Instead of using attributes, you can configure a property as a concurrency token using the Fluent API in EF Core.</p><h4>Example Entity with Fluent API</h4><pre>public class Product<br>{<br>    public int ProductId { get; set; }<br>    public string Name { get; set; }<br>    public int Quantity { get; set; }<br>    public byte[] RowVersion { get; set; }<br>}<br><br>// In the DbContext<br>protected override void OnModelCreating(ModelBuilder modelBuilder)<br>{<br>    modelBuilder.Entity&lt;Product&gt;()<br>        .Property(p =&gt; p.RowVersion)<br>        .IsRowVersion();<br>}</pre><ul><li>The IsRowVersion() method configures the RowVersion property to be used as a concurrency token.</li><li>This is equivalent to using the [Timestamp] attribute.</li></ul><h4>Example Update with Fluent API</h4><pre>try<br>{<br>    using (var context = new YourDbContext())<br>    {<br>        var productId = 1;<br>        var product = context.Products.Single(p =&gt; p.ProductId == productId);<br><br>        product.Quantity -= 5;<br><br>        context.SaveChanges();<br>    }<br>}<br>catch (DbUpdateConcurrencyException ex)<br>{<br>    Console.WriteLine(&quot;Concurrency conflict detected.&quot;);<br>}</pre><ul><li>The process remains the same as with the [Timestamp] approach, but the configuration is done through the Fluent API.</li></ul><h3>5. Retrying Updates Automatically</h3><p>In some scenarios, you may want to retry updates automatically if a concurrency conflict occurs. Below is an example of how to retry an update a few times before failing:</p><pre>public async Task UpdateProductAsync(int productId, int quantityToReduce)<br>{<br>    const int maxRetries = 3;<br>    int attempt = 0;<br>    bool isSuccessful = false;<br><br>    while (attempt &lt; maxRetries &amp;&amp; !isSuccessful)<br>    {<br>        try<br>        {<br>            using (var context = new YourDbContext())<br>            {<br>                var product = await context.Products.SingleAsync(p =&gt; p.ProductId == productId);<br><br>                // Modify the product.<br>                product.Quantity -= quantityToReduce;<br><br>                await context.SaveChangesAsync();<br>                isSuccessful = true;<br>            }<br>        }<br>        catch (DbUpdateConcurrencyException)<br>        {<br>            attempt++;<br>            if (attempt &gt;= maxRetries)<br>            {<br>                Console.WriteLine(&quot;Max retries reached. Could not update the product.&quot;);<br>                throw;<br>            }<br><br>            Console.WriteLine(&quot;Retrying due to concurrency conflict...&quot;);<br>        }<br>    }<br>}</pre><ul><li><strong>Automatic Retry Logic</strong>: This example retries up to three times if a concurrency conflict occurs.</li><li>It uses DbUpdateConcurrencyException to determine when a retry is necessary.</li><li>This pattern is useful when conflicts are expected to be resolved quickly, such as in collaborative applications.</li></ul><h3>Summary of Optimistic Locking Examples</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*iiPW0dILQhDyRLSgTDMJ_Q.png" /></figure><p>These examples cover the common ways to handle optimistic locking with EF Core, allowing your application to detect and handle concurrent changes gracefully. The choice of method depends on the application’s needs and how you want to handle conflicts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd677916ef60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pessimistic Locking in .NET]]></title>
            <link>https://medium.com/@imaanmzr/pessimistic-locking-in-net-4dd45ab53388?source=rss-150b7de8cbc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dd45ab53388</guid>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[pessimistic-locking]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Imaan Mazreati]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 16:40:54 GMT</pubDate>
            <atom:updated>2024-11-03T15:21:36.409Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pessimistic Locking in .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8X8p2Y7NSlUzw9pSJmWMXg.png" /></figure><p>Pessimistic and optimistic locking are two approaches used to manage concurrent access to data in a multi-user environment. They are strategies for ensuring data integrity when multiple transactions or threads attempt to read or write to the same data at the same time. These approaches are commonly used in .NET applications when working with databases.</p><ul><li><strong>Behavior</strong>: Pessimistic locking assumes that conflicts between transactions are likely to occur, so it prevents them by locking data before any modifications are made. When a transaction reads or modifies a record, it places a lock on the data, ensuring that no other transactions can read or modify that data until the lock is released.</li><li><strong>Mechanism</strong>: When a record is locked under pessimistic locking, other transactions attempting to access the same record will either be blocked until the lock is released or receive an error (depending on the lock type).</li><li><strong>Use Case</strong>: Suitable for scenarios where conflicts are frequent, such as high-contention environments where multiple transactions try to update the same records simultaneously.</li><li><strong>Problems</strong>: Can significantly reduce concurrency because it locks records for the entire duration of a transaction, potentially leading to performance bottlenecks and deadlocks if transactions take too long.</li><li><strong>Example Scenario</strong>: In a banking application, when a user transfers money between accounts, the balance of the involved accounts might be locked to ensure that no other transaction can modify them until the transfer is complete, thus preventing issues like double withdrawal.</li></ul><p>Pessimistic locking can be implemented in .NET using TransactionScope and direct SQL statements with locking hints (like WITH (ROWLOCK, XLOCK) in SQL Server). Here’s an example using <a href="http://ado.net/">ADO.NET</a>:</p><pre>using (var connection = new SqlConnection(connectionString))<br>{<br>    connection.Open();<br>    var command = new SqlCommand(<br>        &quot;SELECT * FROM Accounts WITH (UPDLOCK, ROWLOCK) WHERE AccountId = @AccountId&quot;,<br>        connection);<br>    command.Parameters.AddWithValue(&quot;@AccountId&quot;, accountId);<br><br>    using (var reader = command.ExecuteReader())<br>    {<br>        // Read data and perform updates.<br>    }<br>    // Commit transaction when done.<br>}</pre><p>In this example:</p><ul><li>UPDLOCK is used to acquire an update lock, which means that other transactions cannot read or update this record until the current transaction is completed.</li><li>ROWLOCK restricts the lock to a single row instead of locking the entire table.</li></ul><h3>Pessimistic Locking Scenarios</h3><p>In Entity Framework Core (EF Core), direct support for pessimistic locking is not built into the framework itself as it is with some other ORMs, but you can use raw SQL commands or directly apply locks through SQL hints to implement pessimistic locking. Here are some common ways to use pessimistic locking with EF Core:</p><h3>1. Pessimistic Read Lock (WITH (ROWLOCK, HOLDLOCK) or WITH (UPDLOCK) for reading)</h3><ul><li>A pessimistic read lock allows you to lock the row for reading to ensure no other transactions can modify the data while it’s being read.</li><li>Use this if you want to ensure that the data you are reading remains unchanged until the transaction completes.</li></ul><pre>using (var context = new YourDbContext())<br>{<br>    var productId = 1;<br><br>    var product = context.Products<br>        .FromSqlRaw(&quot;SELECT * FROM Products WITH (ROWLOCK, HOLDLOCK) WHERE ProductId = {0}&quot;, productId)<br>        .Single();<br><br>    // Perform operations with the locked product data here.<br><br>    context.SaveChanges();<br>}</pre><ul><li><strong>ROWLOCK</strong>: Locks only the row to avoid locking the entire page or table.</li><li><strong>HOLDLOCK</strong>: Equivalent to using SERIALIZABLE isolation level; it holds the lock until the transaction completes.</li></ul><h3>2. Pessimistic Write Lock (WITH (ROWLOCK, UPDLOCK) for updating)</h3><ul><li>An update lock (UPDLOCK) is commonly used when you intend to read a record and then update it, avoiding conflicts between multiple transactions trying to update the same record.</li><li>This will prevent other transactions from reading the record until the update is completed.</li></ul><pre>using (var context = new YourDbContext())<br>{<br>    var productId = 1;<br><br>    var product = context.Products<br>        .FromSqlRaw(&quot;SELECT * FROM Products WITH (UPDLOCK, ROWLOCK) WHERE ProductId = {0}&quot;, productId)<br>        .Single();<br><br>    // Modify the product data.<br>    product.Quantity -= 10;<br><br>    context.SaveChanges();<br>}</pre><ul><li><strong>UPDLOCK</strong>: Acquires an update lock, allowing the read but blocking others from acquiring locks that could modify the data.</li><li><strong>ROWLOCK</strong>: Restricts the lock to the specific row being accessed.</li></ul><h3>3. Using TransactionScope for Pessimistic Locking</h3><ul><li>With TransactionScope, you can apply pessimistic locking by setting the isolation level of the transaction. This allows you to lock data more explicitly during the transaction.</li><li>For example, using the Serializable isolation level will prevent other transactions from reading or writing data that is being read by the current transaction.</li></ul><pre>using System.Transactions;<br><br>using (var transaction = new TransactionScope(<br>    TransactionScopeOption.Required,<br>    new TransactionOptions<br>    {<br>        IsolationLevel = IsolationLevel.Serializable<br>    }))<br>{<br>    using (var context = new YourDbContext())<br>    {<br>        var productId = 1;<br>        var product = context.Products.Single(p =&gt; p.ProductId == productId);<br><br>        // Perform operations on the product.<br>        product.Quantity -= 10;<br><br>        context.SaveChanges();<br>    }<br><br>    transaction.Complete();<br>}</pre><ul><li>Serializable Isolation Level: Ensures the highest level of isolation, preventing other transactions from reading or modifying the data being processed by the current transaction until it completes.</li></ul><h3>4. Explicit Locking with SQL Server Hints (XLOCK for exclusive locks)</h3><ul><li>An exclusive lock prevents other transactions from reading or writing to the locked row. This is useful when you want to ensure that no other transaction can access the data while it’s being modified.</li></ul><pre>using (var context = new YourDbContext())<br>{<br>    var productId = 1;<br><br>    var product = context.Products<br>        .FromSqlRaw(&quot;SELECT * FROM Products WITH (XLOCK, ROWLOCK) WHERE ProductId = {0}&quot;, productId)<br>        .Single();<br><br>    // Modify the product data.<br>    product.Quantity -= 10;<br><br>    context.SaveChanges();<br>}</pre><ul><li><strong>XLOCK</strong>: Acquires an exclusive lock, ensuring that no other transactions can read or modify the row.</li><li><strong>ROWLOCK</strong>: Applies the lock at the row level to avoid locking the entire table.</li></ul><h3>5. Using BeginTransaction with Isolation Levels in EF Core</h3><ul><li>You can also use BeginTransaction on the database connection to control isolation levels manually.</li></ul><pre>using (var context = new YourDbContext())<br>{<br>    using (var transaction = context.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))<br>    {<br>        var productId = 1;<br><br>        var product = context.Products<br>            .Single(p =&gt; p.ProductId == productId);<br><br>        // Perform operations on the product.<br>        product.Quantity -= 10;<br><br>        context.SaveChanges();<br><br>        transaction.Commit();<br>    }<br>}</pre><ul><li>This example achieves a similar effect to using TransactionScope but is more tightly coupled to the EF Core context. It uses the Serializable isolation level to ensure the highest level of transaction isolation.</li></ul><h3>6. Custom Raw SQL for UPDATE with Locking</h3><ul><li>For more complex scenarios, you might need to directly execute an UPDATE statement with a locking hint using ExecuteSqlRaw.</li></ul><pre>using (var context = new YourDbContext())<br>{<br>    var productId = 1;<br><br>    context.Database.ExecuteSqlRaw(<br>        &quot;UPDATE Products WITH (XLOCK, ROWLOCK) SET Quantity = Quantity - 10 WHERE ProductId = {0}&quot;,<br>        productId);<br><br>    // No need for context.SaveChanges() since we&#39;re using raw SQL.<br>}</pre><ul><li>XLOCK: Locks the row exclusively during the update, ensuring that no other transactions can access it while the update is being processed.</li></ul><h3>Summary of Locking Hints Used</h3><ul><li><strong>ROWLOCK</strong>: Locks a single row, avoiding locking an entire page or table.</li><li><strong>UPDLOCK</strong>: Acquires an update lock on a row or table, preventing modifications by others until the lock is released.</li><li><strong>XLOCK</strong>: Places an exclusive lock on the data, preventing both reads and writes by other transactions.</li><li><strong>HOLDLOCK</strong>: Equivalent to SERIALIZABLE isolation level, keeping the lock until the transaction is complete.</li></ul><h3>Key Considerations</h3><ul><li>Using pessimistic locking can reduce the number of conflicts but may result in <strong>reduced concurrency</strong> and <strong>potential deadlocks</strong>, especially in high-traffic environments.</li><li>When using raw SQL for locking, make sure that the locking hints match your business logic requirements and are tested for performance impact.</li><li>It’s important to understand the locking mechanism of SQL Server when applying these strategies to avoid unintended blocking or deadlocks.</li></ul><p>Pessimistic locks should be used when you are certain that data contention is high, and you cannot afford to have other transactions read or modify the data while you are working with it. This is most critical in financial transactions or operations that require strict consistency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dd45ab53388" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>