<?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 Mohannad A. Karim on Medium]]></title>
        <description><![CDATA[Stories by Mohannad A. Karim on Medium]]></description>
        <link>https://medium.com/@mohannad.a.karim?source=rss-e6a1580cdb7d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PGi_7kX-1-jStjUJXtNTew.png</url>
            <title>Stories by Mohannad A. Karim on Medium</title>
            <link>https://medium.com/@mohannad.a.karim?source=rss-e6a1580cdb7d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 04:23:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohannad.a.karim/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[Differential Privacy: How Your Data Gets Analyzed Without Revealing Who You Are]]></title>
            <link>https://medium.com/@mohannad.a.karim/differential-privacy-how-your-data-gets-analyzed-without-revealing-who-you-are-abbbb03dc889?source=rss-e6a1580cdb7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/abbbb03dc889</guid>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Mohannad A. Karim]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 17:18:31 GMT</pubDate>
            <atom:updated>2025-10-31T17:18:31.135Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Apple, Google, and other tech giants are using advanced math to learn from your data while keeping you anonymous</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTH7nh0VMA30-OjrkGVfmA.png" /></figure><p>You’ve probably seen those prompts: “Help us improve our product by sharing usage data.” Maybe it’s your phone’s keyboard learning which words you type, or your browser tracking which features you use, or your smart home device trying to understand voice commands better.</p><p>Companies genuinely need this data to build better products. They need to know which features people actually use, where things break, what patterns emerge across millions of users.</p><p>But here’s the uncomfortable part: even when they promise to “anonymize” your data, that’s often not as protective as it sounds.</p><p><strong>Netflix</strong> released “anonymized” viewing data for a research competition. Researchers were able to re-identify specific users. <strong>AOL</strong> published “anonymous” search logs. People got identified. Supposedly anonymous medical records have been linked back to individuals by cross-referencing with other public datasets.</p><p>Stripping names and obvious identifiers just isn’t enough.</p><p>This is the problem <strong>differential privacy</strong> solves. It’s a mathematical framework that lets companies actually learn from aggregate patterns across millions of users while making it provably impossible to extract information about any individual — even if an attacker has access to every other database on the planet.</p><p>It’s why <strong>Apple</strong> can improve your keyboard predictions without seeing what you type, why <strong>Google</strong> can understand <strong>Chrome</strong> usage without tracking your browsing, and why the <strong>Census Bureau</strong> can publish demographic statistics without revealing anyone’s personal information.</p><h3>The basic idea</h3><p>The concept is surprisingly straightforward: add carefully calibrated random noise to data so you can still extract accurate statistics from large datasets, but individual records become impossible to identify.</p><p>The noise isn’t just random though. It’s precisely calculated based on something called a <strong>“privacy budget.”</strong> Think of it like a number that quantifies how much privacy you’re trading for accuracy. This number is usually called <strong>epsilon</strong>, or <strong>ε</strong> if you want to be fancy about it.</p><p>Smaller epsilon means stronger privacy but noisier results. Larger epsilon gives more accurate results but weaker privacy guarantees. It’s always a tradeoff.</p><p>Here’s a simple example to make this concrete. Say you want to know the average salary in a company database. Instead of returning the exact number, a differentially private system would calculate the true average, add some random noise to it, then return that noisy result.</p><p>With strong privacy settings, you might add noise of plus or minus $10,000. With weaker privacy, maybe plus or minus $2,000. Either way, you get a useful answer about salary ranges without exposing anyone’s specific information.</p><p>What makes this different from just “adding random noise and hoping for the best” is the mathematical guarantee behind it. The formal definition says that for any two datasets differing by one person, the probability of getting any particular output is almost identical.</p><p>In plain English: looking at the output tells you virtually nothing about whether any specific person is in the dataset.</p><h3>Why cloud computing makes this critical</h3><p><strong>Cloud infrastructure</strong> fundamentally changed how we handle data. Your information isn’t sitting on a single server anymore. It’s distributed across regions, cached in multiple places, processed by different services, and potentially accessed by various teams and analytics tools.</p><p>This creates privacy problems that old approaches just can’t handle.</p><p>Scale makes traditional methods impractical. Manual review doesn’t work when you’re dealing with <strong>petabytes</strong> of data from millions of users. You need automated privacy that can work at cloud scale without someone having to personally check every query.</p><p>Then there’s the access problem. Different teams need the data. Different services need to process it. Sometimes even different companies — like your cloud provider — need to touch it. Each access point is a potential privacy leak. Differential privacy lets you grant access while maintaining mathematical privacy guarantees.</p><p>But the real issue is data combination. This is where most privacy breaks down in practice. One dataset alone might seem totally safe. But combine it with another dataset, then maybe a third public dataset, and suddenly you can start identifying specific individuals. Differential privacy has built-in <strong>composition properties</strong> that track total privacy loss across multiple analyses.</p><p>And then there’s regulation. <strong>GDPR</strong>, <strong>CCPA</strong>, and similar laws now require actual proof that you’re protecting user data. Just saying “we removed the names” isn’t sufficient anymore. You need provable guarantees, which is exactly what differential privacy provides.</p><h3>How the privacy budget works</h3><p>The privacy budget — that epsilon value — is the core concept that makes everything work. Every query or analysis you run consumes some of this budget. Once you’ve spent it all, you can’t run more queries without either reducing privacy or somehow refreshing the budget.</p><p>There are different approaches to implementing this, and they each have their own tradeoffs.</p><p>The most common approach is called <strong>central</strong> or <strong>global differential privacy</strong>. Here, the organization collecting data adds noise before releasing any results. Users send their raw data, the curator analyzes it privately, then publishes the noisy results. This is what the Census Bureau uses. It’s efficient and works well, but you have to trust the data collector to actually apply the privacy protections.</p><p>Then there’s <strong>local differential privacy</strong>, which is more extreme. With this approach, users add noise to their own data before sending it anywhere. Even the data collector never sees the true values. Apple uses this for keyboard analytics and Safari browsing data. The tradeoff is brutal though — you need significantly more noise to get the same privacy level, which means you need way larger datasets to extract anything useful.</p><p>The <strong>shuffle model</strong> sits in the middle. Users add some noise locally, then a shuffler randomizes who sent what, then the curator analyzes everything. This can give you better accuracy than pure local differential privacy while still limiting what the curator can learn about individuals.</p><h3>The math underneath (explained simply)</h3><p>The actual mechanisms that add noise come in a few different flavors, but they’re all based on similar principles.</p><p>The <strong>Laplace mechanism</strong> is one of the most common. It adds noise from what’s called a Laplace distribution, which has this specific bell-curve-like shape. This works well for numerical queries like sums or averages where the sensitivity is unbounded.</p><p>The <strong>Gaussian mechanism</strong> is similar but uses Gaussian noise instead — the classic bell curve you might remember from statistics class. This can give tighter privacy bounds in some cases, though it requires slightly different privacy definitions to work with.</p><p>Then there’s the <strong>exponential mechanism</strong>, which handles a completely different type of query. Instead of trying to add noise to a number, this is for choosing from discrete options. Like “which category is most common?” Instead of adding noise to the answer directly, it randomly selects answers with probability proportional to their accuracy. The most accurate answer is most likely to get picked, but not guaranteed.</p><p>There’s also something called <strong>report noisy max</strong> that combines these approaches for finding top-k results while maintaining privacy. It’s useful when you want to know the most popular items or the highest-ranking categories.</p><p>Don’t worry if the mathematical details feel fuzzy — the key takeaway is that there are different techniques for different types of queries, and they all work by adding carefully calibrated noise.</p><h3>What this means for analyzing data</h3><p>If you’re someone who actually works with data, differential privacy fundamentally changes your workflow, especially in cloud environments.</p><p>The biggest shift is psychological. You’re used to exploring data freely, running dozens of queries to understand patterns, drilling down into interesting subsets. That doesn’t work anymore because every query costs privacy budget. You need to be deliberate and thoughtful about what you’re querying.</p><p>The good news is that <strong>aggregate statistics</strong> work great. Population counts, averages, percentages, trends over time — these all work well with differential privacy when you have large enough datasets. The noise becomes negligible compared to your sample size, so you still get accurate insights about broad patterns.</p><p>The frustrating part is that <strong>granular analysis</strong> gets really difficult. You can’t drill down to small subgroups or rare events because the noise overwhelms the actual signal. No more “show me all users who did X in this specific city last week.” You can know how many people did X across all cities combined, but you can’t identify specific cases or small groups.</p><p>Machine learning with differential privacy is totally possible, but it requires specialized algorithms. The main approach is called <strong>DP-SGD</strong> — <strong>differentially private stochastic gradient descent</strong>. You add noise during the training process in a way that provides privacy guarantees. The models end up slightly less accurate than they would be without privacy, but researchers are closing that gap with better techniques.</p><p>There’s also this composition problem to deal with. Running multiple related analyses erodes privacy more than running a single analysis would. There are mathematical theorems that bound the total privacy loss, but in practice this means you need to carefully budget which analyses are most important to your business.</p><h3>Protection against attacks</h3><p>Differential privacy isn’t just about being a good citizen with user data. It also blocks specific types of attacks that traditional anonymization can’t handle.</p><p><strong>Re-identification attacks</strong> are when someone tries to figure out whose data is in your dataset by cross-referencing it with external information they already have. This has worked on supposedly “anonymous” datasets in the past — remember those Netflix and AOL examples from earlier. Differential privacy mathematically prevents these attacks from succeeding.</p><p><strong>Membership inference</strong> is another attack vector. Here, attackers try to determine if a specific person’s data was used to train a machine learning model. This matters because membership itself can reveal sensitive information. If I can prove your medical data was in a cancer research dataset, that tells me something about you even if I can’t see your actual records. Training with differential privacy prevents this.</p><p><strong>Reconstruction attacks</strong> are particularly nasty. Given enough query results over time, attackers can sometimes piece together individual records bit by bit. The privacy budget system limits how many queries can be answered, which prevents reconstruction attempts from getting enough information to succeed.</p><p><strong>Model inversion</strong> is the machine learning version of this problem. Attackers try to extract training data from a deployed model. Differential privacy bounds how much information about the training data can leak through the model’s parameters or predictions.</p><h3>The hard parts of implementation</h3><p>Getting differential privacy working in production isn’t as simple as flipping a switch. There are real challenges that organizations struggle with.</p><p>Picking the right epsilon value is genuinely hard. There’s no universal “correct” answer that works for everyone. Apple uses values between 2 and 8 depending on what feature they’re protecting. The Census Bureau used 19.61 for the 2020 census, which drew significant criticism from researchers who felt it was too high and provided weaker privacy than it should. Google uses different values for different products. It all depends on how sensitive your data is, how large your dataset is, and what you’re trying to learn from it.</p><p>Privacy budget management needs real infrastructure. Who gets to run queries? How much budget does each team get? What happens when someone wants to run a critical business analysis but all the budget has been spent? You need governance processes and technical tooling that most organizations just don’t have built yet.</p><p>The existing tools you’re already using don’t support differential privacy out of the box. Standard <strong>SQL databases</strong>, business intelligence platforms, data science tools — none of them were designed with this in mind. You need either completely new tools like Google’s <strong>PipelineDP</strong> or the open-source <strong>OpenDP</strong> project, or you need to make significant modifications to your existing stack. Some companies like <strong>Snowflake</strong> are starting to add differential privacy features natively, but adoption across the industry is still pretty early.</p><p>Performance overhead matters when you’re operating at scale. Computing noise values, tracking budget consumption, enforcing access controls — all of this adds latency and computational cost. For systems handling millions of queries per second, that overhead starts to become significant.</p><p>The math is legitimately difficult. Most engineers and data scientists haven’t studied differential privacy in school. It requires understanding probability theory, information theory, and some cryptography. Building internal expertise takes time, training, and hiring people with the right background.</p><p>Debugging becomes harder too. When a differentially private query returns unexpected results, how do you know if it’s because the underlying data is genuinely weird, or if it’s just noise? Validating your analyses is tricky when the results are intentionally randomized.</p><h3>How cloud platforms are approaching this</h3><p>Different cloud providers are tackling differential privacy in different ways, and some patterns are emerging.</p><p>The most common approach is <strong>privacy-preserving APIs</strong>. Instead of giving analysts direct access to databases, you provide APIs that enforce differential privacy automatically. Analysts submit their queries through the API, the system checks available budget, adds appropriate noise, and returns results. This centralizes the enforcement logic and makes auditing much easier.</p><p><strong>Trusted execution environments</strong> come up a lot in this context. Technologies like <strong>Intel SGX</strong> or <strong>AWS Nitro Enclaves</strong> provide hardware-protected computation zones. These aren’t differential privacy tools themselves, but they’re often used in combination with it. The trusted execution environment protects data while it’s being computed on, and differential privacy protects against statistical inference from the results. You can run the most privacy-critical parts of your pipeline inside these protected environments where even the cloud provider can’t peek at what’s happening.</p><p><strong>Federated learning</strong> combined with differential privacy is gaining traction for scenarios where data legally can’t move. Different sites train local models with differential privacy applied, then only the noised model updates get shared to a central location. No raw data ever leaves any site, which matters a lot for healthcare, finance, and international data transfers.</p><p><strong>Synthetic data generation</strong> is emerging as an interesting alternative. Instead of adding noise to query results, you generate an entirely synthetic dataset that has the same statistical properties as your real data. Analysts can work with the synthetic data just like normal data, and it’s provably private. The challenge is generating high-quality synthetic data that preserves all the complex relationships and patterns from the original.</p><h3>Where this is all heading</h3><p>A few trends are worth paying attention to if you care about privacy technology.</p><p>Machine learning privacy is improving rapidly. Newer techniques like <strong>PATE</strong> — that’s <strong>Private Aggregation of Teacher Ensembles</strong> — and continuous improvements to <strong>DP-SGD</strong> are closing the accuracy gap. You can train surprisingly good models with strong privacy guarantees now, which wasn’t really possible just a few years ago.</p><p>Automated privacy budgeting is becoming a thing. Instead of having humans manually decide how to allocate privacy budget across different analyses, systems are starting to use optimization algorithms to allocate it automatically based on query patterns and business importance.</p><p>Standardization is actually happening, which is huge. The <strong>OpenDP</strong> project is building open-source libraries and frameworks. <strong>ISO</strong> and other standards bodies are working on differential privacy standards. This should make adoption much easier for organizations that don’t have huge research teams.</p><p>Regulatory recognition is increasing too. More jurisdictions are explicitly mentioning differential privacy in data protection regulations or accepting it as a valid privacy-preserving technique. It’s moving from being a research concept to being recognized practice.</p><p>Better tooling is coming as cloud platforms add native support. The easier it is to use, the more people will adopt it. More adoption means more real-world testing. More testing leads to better tools. It’s a positive feedback loop that’s just starting to spin up.</p><h3>Why any of this matters</h3><p>Differential privacy isn’t a magic solution that fixes all privacy problems. It doesn’t prevent data breaches. It doesn’t stop malicious insiders. It doesn’t handle every possible privacy scenario you might encounter.</p><p>But it does something genuinely valuable: it makes privacy <strong>mathematically provable</strong>. Not “we tried our best” or “we follow industry standard practices.” An actual mathematical proof that releasing your data analysis leaks less than epsilon amount of information about any individual person.</p><p>When <strong>Apple</strong> improves <strong>iOS</strong> features based on how millions of people use their phones, differential privacy is how they do it without seeing what any individual person is doing. When researchers analyze census data to inform public policy, differential privacy protects individual responses. When tech companies train <strong>AI models</strong> on user data, differential privacy — at least in theory — prevents those models from memorizing and regurgitating specific examples from the training set.</p><p>The tradeoffs are absolutely real. You lose some accuracy. You can’t do certain types of detailed analysis. Implementation is complex and expensive. The costs aren’t trivial.</p><p>But you get mathematical certainty about privacy, which is incredibly rare in computer security. Most security measures are about making attacks harder or more expensive. Differential privacy actually provides a proof that certain attacks are impossible, regardless of how much computational power an attacker has.</p><p>As more critical data moves to the cloud and privacy regulations continue to tighten around the world, having tools that provide <strong>provable privacy guarantees</strong> becomes increasingly important. Differential privacy is one of the very few techniques that actually delivers on that promise.</p><p>It’s not perfect. It’s not easy. But it works.</p><p><em>Have experience implementing differential privacy? Thoughts on the accuracy/privacy tradeoffs? Comments are open.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abbbb03dc889" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computing on Secret Data: The Magic of Homomorphic Encryption Explained]]></title>
            <link>https://medium.com/@mohannad.a.karim/computing-on-secret-data-the-magic-of-homomorphic-encryption-explained-efb54294da45?source=rss-e6a1580cdb7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb54294da45</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[software-security]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Mohannad A. Karim]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 16:41:59 GMT</pubDate>
            <atom:updated>2025-09-15T13:29:09.710Z</atom:updated>
            <content:encoded><![CDATA[<h4>Have you ever thought it would be great to analyze data without ever seeing it? Let me introduce you to one of cryptography’s most fantastical innovations.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6JtPQ5-ftlYS3Cl1" /><figcaption>Photo by <a href="https://unsplash.com/@fabioha?utm_source=medium&amp;utm_medium=referral">fabio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To illustrate, imagine you have a locked safe which contains some documents that are important to you. Normally, if someone wanted to work with your documents — like adding some numbers or finding a pattern in your data — they would need you to open the safe first. But what if I told you there’s a “magic safe” where people can do calculations with your documents, without ever opening the safe. Amazingly, they still get the right answer.</p><p>While I realize there might be concerns about “magic”, you’re going to be surprised about the “safe” in homomorphic encryption; we’re talking about encrypted data on computers rather than physical safes.</p><h3>Before We Discuss Homomorphic Encryption</h3><p>Before we talk about anything fanciful or magical, it’s good to agree on some basics regarding regular encryption.</p><p>When you send a message in WhatsApp or make an online purchase, the data is scrambled (encrypted) to ensure that whoever is spying on the internet sees nothing but gibberish. No one can make sense of that gibberish unless you have the proper key to unscramble (decrypt) the message.</p><p>Encryption works really well for storing and sending data; the problem comes when you want to actually <strong>do</strong> something with that data.</p><p>For example, let’s say you’re a hospital looking to analyze patient records for patterns of disease, but you want to take advantage of the powerful computing resources of Google.</p><blockquote>Usually you’d need to:</blockquote><blockquote>Encrypt your data to send it securely to Google. Google would decrypt it to analyze it (uh oh — now Google has can see all your patient data) Google would presumably encrypt the result back to your organization.</blockquote><p>See the problem, right? There’s that awkward moment in step #2,where your sensitive data is just sitting there, fully exposed, on someone else’s computer.</p><h3>Along comes Homomorphic Encryption: The Game Changer</h3><p>Now, what if Google could actually do their analysis on your data in encrypted form — without ever decrypting? They would get your patient records in encrypted form, crunch the numbers in encrypted form, and send you back encrypted results. Once you decrypted those results, they would be exactly what you would have gotten had Google analyzed your raw data.</p><p>That’s homomorphic encryption in a nutshell.</p><p>The term may sound complicated, but, “homomorphic” means “same shape” in Greek. The idea is that the mathematical operations maintain their “shape” when operating on encrypted data.</p><h3>A Simple Example to Blow Your Mind</h3><p>Let’s provide you an example that makes this concept hit home.</p><p>You and a friend want to know your combined salary, but without one of you revealing your own salary to the other (possibly you are both considering new jobs and want to know if you are being paid fairly)</p><p>Using encryption, this is impossible with either one of you seeing the other’s salary at some point. With homomorphic encryption:</p><p>You encrypt your salary: <strong><em>E(YourSalary)</em></strong><em> </em>Your friend encrypts their salary: <strong><em>E(FriendSalary)</em></strong> Somebody (maybe a trusted third party, or one of you) does the addition of the encrypted numbers: <strong><em>E(YourSalary) + E(FriendSalary) = E(YourSalary + FriendSalary)</em></strong></p><p>Then, you both jointly decrypt the output and you get to learn your combined salary. At no point did anyone see anyone else’s salary, but you were able to learn the combined one. That’s pretty neat, right?</p><h3>Why This Matters in Practice</h3><p>This isn’t just an interesting mathematical trick — it helps solve some really significant problems:</p><p><strong>Medical Research</strong> Hospitals could work together on research without sharing patient-level data. Think of ten hospitals working together discovering which treatments that are best for cancer patients — and not having to worry about that patient data ever leaving the individual hospital in an unencrypted format.</p><p><strong>Financial Services</strong> Banks could detect fraud patterns by utilizing transaction data across organizations without actually sharing customer information with each other.</p><p><strong>Personal Privacy</strong> You could have get recommendations on Netflix, or Spotify to find new shows or new music without those companies ever seeing your actual viewing or listening history — just an encrypted version.</p><p><strong>Cloud Computing</strong> Companies could outsource significant computing to Amazon or Google without worrying about either of those companies inspecting or seeing their sensitive business data.</p><h3>The Reality Check: It’s Not a Magic Wand (Yet)</h3><p>Now before you get too excited and believe it’s some sort of Nirvana, let’s take a step back to reality. Homomorphic encryption does exist and is functional. But it has some significant limitations at present:</p><h4><strong>It is slow. Super slow.</strong></h4><p>We’re talking about operations that could take 1,000 or even 10,000 times longer than normal. That addition that happens instantaneously at normal numbers could take several milliseconds at encrypted numbers. Expand that to millions of records being analyzed, and you’re looking at computations that are going to take hours/days to complete instead of minutes.</p><h4><strong>The data is much larger.</strong></h4><p>Encrypted data take about 10–15 times the storage size of regular data. So your 1GB database has become a 15GB database.</p><h4><strong>Not all operations work equally well.</strong></h4><p>Some mathematical operations translate nicely to encrypted data, but others do not. Basic arithmetic (addition, multiplication) work fine, but complicated logic, comparisons, and conditional statements don’t work as well, if at all.</p><h4><strong>It’s technically difficult.</strong></h4><p>To implement this stuff in the right way takes serious cryptography skill. If you mess up the parameters, a “perfectly fine” encryption is now highly breakable.</p><h3>The Flavors</h3><p>Just like ice cream, homomorphic encryption has its flavors:</p><h4><strong>Partially Homomorphic:</strong></h4><p>Can do one kind of operation incredibly well. Some systems can add encrypted numbers, some can multiply, but not both.</p><h4><strong>Somewhat Homomorphic:</strong></h4><p>Can do addition and multiplication, but only to a limit. Each operation adds “noise” to the data, and once there is too much noise to the data, no one can read anything.</p><h4><strong>Fully Homomorphic:</strong></h4><p>The holy grail! Can be proven to do any computation on encrypted data. This is where all hype is being generated, but it is also the slowest and most complex to work with.</p><h3>Who is Actually using it?</h3><p>Despite the limitations, already some organizations are using homomorphic encryption for actual applications:</p><p><strong>Banks</strong> are using it for regulatory reporting — they can prove compliance with regulators without exposing customer data</p><p><strong>Healthcare researchers</strong> are collaborating potentially on drug discovery while sharing encrypted patient data</p><p><strong>Government agencies</strong> are analyzing classified information without revealing their sources</p><p><strong>Tech companies</strong> are investigating privacy-preserving machine learning</p><p>The key is finding appropriate applications, where the privacy benefit outweighs the performance cost.</p><h3>What is Coming Next?</h3><p>The good news is that the technology is significantly improving</p><p><strong>Hardware acceleration</strong> is coming. Intel and others are building chips specifically designed for homomorphic encryption. Early tests show improvements of 100–1000x.</p><p><strong>Better algorithms</strong> are being developed by researchers around the world. The mathematics is becoming more efficient, and the implementations are becoming faster.</p><p><strong>Easier tools</strong> are being built. You will no longer require a PhD in cryptography to work with this stuff — companies are creating user-friendly libraries and platforms.</p><p><strong>Industry adoption</strong> is happening. Microsoft, Google, IBM, and Amazon are all investing in the technology.</p><h3>The Bigger Picture</h3><p>Here’s why I believe homomorphic encryption is so important — it could dramatically change the business model for the internet.</p><p>Most online “free” service today, are paid for by your data. Google, Facebook and others provide services, while collecting, analyzing and reporting of personal information about you.</p><p>Homomorphic Encryption opens the door for a different model. You could get all the benefits of data analytics — recommendations based on preferences, better services, improved healthcare — while retaining mathematical control over your private information.</p><p>Imagine a world where:</p><p>Netflix would provide you great movie recommendations without ever seeing any of the movies that you actually watch. Your fitness app helps you get healthy, without knowing your medical history. Financial services protect you from fraud, without knowing your spending habits. Researchers cure diseases using your genetic information without having to access it.</p><h3>Does it Matter Right Now?</h3><p>If you don’t work as a cryptographer or plan to go work at a tech company you are probably thinking, “This is interesting but what does it mean for me?”</p><p>The point here is that most revolutionary technologies start slow, costly and limited. The first computers took up entire rooms and were less powerful than your smartphone. The early internet was slow and cumbersome. Electric vehicles were just the whims of enthusiasts.</p><p>But the pattern holds true: the technology catches up and improves, the cost comes down, and before long it isn’t even a thought because it is so embedded in our lives.</p><p>I think homomorphic encryption is on that path too. It won’t change your everyday life tomorrow — but it’s possible it could lead to a more private and safe digital world for you in the years to come.</p><h3>The Bottom Line</h3><p>Homomorphic is one of those things that seems like science fiction but actually works. It is not ready for prime time in many applications yet, but it is very much real, developing rapidly, and may solve some of the largest rising privacy problems in our increasingly digital era. The gist is quite basic: math that lets you do computations on secrete data and get the correct results without revealing the secrets ever. The implementation is complicated, but the ramifications are staggering.</p><p>There are real and considerable constraints — performance penalties, storage overhead, implementation complexity, and new security challenges all serve as barriers to adoption. But the development trajectory is promising, with hardware acceleration, algorithmic advances, and industry backing all suggesting greater substantive applicability in the next few years.</p><p>Industries are adopting at different rates depending on their risk tolerance and privacy needs. Financial services and tech companies are moving quickly, healthcare is moving quickly, while government is slower but predictable.</p><p>Whether it’s your personal privacy that has you worried, your interest in the next technological advancement, or merely your interest in new math breakthroughs that may fundamentally change digital society, there are reasons to pay attention to homomorphic encryption. It could be one path to a future where we still can have our digital cake and eat it too — gain the benefits of data analysis while getting our private information truly private. And in a world where we are bombarded with headlines of data breaches every week, restless about the tension between privacy and utility, that is a future worth pursuing.</p><p>The organizations and individuals that start to comprehend this technology now, while it is still developing, might be in possession of substantial advantages once privacy-preserving computation, for example, becomes a commonplace utility. Much like those who understood, really comprehended the implications of the internet in the early 90’s and positioned themselves nicely for the forthcoming digital transformation.</p><p>Want to learn more? The field is developing fast, with new iterations coming out all the time. Watch for research from universities and companies such as Microsoft, IBM, and Google — they are rushing to make this technology faster, easier, and more useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb54294da45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eventual Consistency: Balancing Scalability and Reliability]]></title>
            <link>https://medium.com/@mohannad.a.karim/eventual-consistency-balancing-scalability-and-reliability-15e1b349806a?source=rss-e6a1580cdb7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/15e1b349806a</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Mohannad A. Karim]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 15:33:03 GMT</pubDate>
            <atom:updated>2025-01-06T15:33:03.049Z</atom:updated>
            <content:encoded><![CDATA[<h4>Eventual consistency might sound like a compromise, but it’s a hero in disguise for distributed systems. In a world where instant updates are often impractical, this principle keeps things running smoothly. Let’s dive into what it really means, why it’s so important, and how it operates in the background.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPsMXLzQe8tRWcluCSUPAg.jpeg" /><figcaption>Image Source: <a href="https://www.freepik.com/free-photo/digital-world-banner-background-remixed-from-public-domain-by-nasa_16016436.htm#fromView=search&amp;page=1&amp;position=2&amp;uuid=b086c1e1-43b8-41af-97d2-058de84c7817&amp;new_detail=true">FREEPIK</a></figcaption></figure><h3>What is Consistency?</h3><p>In simple terms, consistency ensures that your data isn’t lying to you. It’s one of the ACID properties (Atomicity, Consistency, Isolation, Durability) that guarantees reliable database transactions. But consistency isn’t just a checkbox — it’s a constant balancing act between accuracy and performance.</p><h3>Data Consistency</h3><p>Data consistency is what holds your database together:</p><ul><li><strong>Multiple Viewpoints</strong>: Consider your database as a sort of jigsaw puzzle composed of many pieces. If any one of those pieces were to change in some manner, the entire picture would need to shift.</li><li><strong>Consistency is User Defined</strong>: Database designers create rules to ensure everything stays in harmony, like foreign key constraints.</li></ul><h3>Read Consistency</h3><p>Read consistency answers a simple question: <em>if one transaction updates data, how soon can others see the change?</em></p><h3>The Catch in Scaled Systems</h3><p>Distributed systems introduce new challenges:</p><ul><li><strong>Scaling Horizontally</strong>: When data is spread across multiple nodes, keeping everything perfectly synchronized takes time.</li><li><strong>Caching</strong>: Cached data might lag behind reality, creating temporary inconsistencies.</li></ul><h3>Enter Eventual Consistency</h3><blockquote>Eventual consistency doesn’t promise instant results — but it does promise eventual harmony. It’s the idea that while data might be inconsistent for a short time, it will eventually align across all nodes.</blockquote><h3>How Eventual Consistency Works</h3><p>Picture a distributed system with a load balancer directing traffic to multiple database instances. Here’s what happens:</p><ol><li>A change is made to one instance.</li><li>The update gradually propagates to the other instances until everything matches.</li></ol><h3><strong>Note:</strong></h3><blockquote>Atomic transactions are the backbone of eventual consistency. Without atomicity, partial updates could corrupt your database, defeating the whole purpose.</blockquote><h3>Everyday Examples</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTp8b6-dlQR2GT1jo-0mGw.png" /></figure><p>You encounter eventual consistency more often than you think:</p><ul><li><strong>Content Delivery Networks (CDNs)</strong>: When you visit a website, cached content might not immediately reflect the latest updates.</li><li><strong>Distributed Databases</strong>: Systems like DynamoDB and Cassandra prioritize availability, ensuring updates are distributed over time.</li><li><strong>Social Media Platforms</strong>: Ever notice a delay in likes or comments syncing across devices? That’s eventual consistency at work!!</li></ul><h3>Why Eventual Consistency Matters</h3><p>Eventual consistency isn’t just a technical concept — it’s a design philosophy. By embracing it, you can:</p><ul><li><strong>Build Global Systems</strong>: Serve millions of users without sacrificing performance.</li><li><strong>Stay Resilient</strong>: Keep your systems running smoothly, even when parts of the network fail.</li></ul><h3>Wrapping It Up</h3><p>Eventual consistency isn’t about settling for less. It’s about making smart trade-offs to ensure your systems are scalable, reliable, and user-friendly. By understanding and applying this principle, you can design systems that thrive in the real world — where perfection is rare, but resilience is everything.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15e1b349806a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Isolation in Databases: The Unsung Hero of ACID Properties]]></title>
            <link>https://medium.com/@mohannad.a.karim/understanding-isolation-in-databases-the-unsung-hero-of-acid-properties-7f57f6a91c72?source=rss-e6a1580cdb7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f57f6a91c72</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Mohannad A. Karim]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 15:27:20 GMT</pubDate>
            <atom:updated>2025-01-03T15:27:20.154Z</atom:updated>
            <content:encoded><![CDATA[<h4>When discussing databases, the ACID properties — Atomicity, Consistency, Isolation, and Durability — form the backbone of transactional integrity. Among these, the <strong>Isolation</strong> property often remains misunderstood and underrated, despite being critical for ensuring correctness in concurrent environments. This article delves deep into the concept of isolation, read phenomena, and how various isolation levels address them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQ70uTqEASoK9JBX5B6Vcg.jpeg" /><figcaption>Image from <a href="https://www.freepik.com/free-ai-image/blockchain-technology-cartoon-illustration_208594059.htm#fromView=search&amp;page=1&amp;position=8&amp;uuid=2ecdb0b5-a7a9-4d64-9056-34c8b4337989&amp;new_detail=true">FREEPIK</a></figcaption></figure><h4>What is Isolation?</h4><p>Isolation answers a crucial question: <em>Can my in-flight transaction see changes made by other transactions?</em> In a multi-transaction environment, isolation ensures that intermediate states of a transaction are not visible to others, preventing potential inconsistencies and conflicts.</p><p>Without proper isolation, the database’s reliability can suffer due to phenomena such as:</p><ol><li><strong>Dirty Reads</strong>: When a transaction reads data that another transaction has not yet committed. This data could be rolled back or committed, leading to potential inconsistencies.<br><strong>Example</strong>: Transaction A updates a customer’s account balance from $100 to $150 but has not yet committed. Transaction B reads the balance as $150, but Transaction A later rolls back, reverting the balance to $100. Transaction B used incorrect data.</li><li><strong>Non-Repeatable Reads</strong>: When a transaction reads the same row twice but gets different results due to updates made by other transactions in between.<br><strong>Example</strong>: Transaction A reads a product’s price as $50. Transaction B updates the price to $60 and commits. When Transaction A reads the price again, it sees $60, leading to inconsistent results within the same transaction.</li><li><strong>Phantom Reads</strong>: When a transaction sees new rows inserted by another transaction between two identical queries.<br><strong>Example</strong>: Transaction A queries all orders where status = &#39;pending&#39;. Transaction B inserts a new pending order and commits. When Transaction A repeats the query, it sees the new order, even though it didn’t exist at the start of the transaction.</li><li><strong>Lost Updates</strong>: When concurrent transactions overwrite each other’s updates without proper handling.<br><strong>Example</strong>: Transaction A reads a product’s stock as 100 and decrements it by 10. Transaction B also reads the stock as 100 and decrements it by 5. Both transactions write their results, and the final stock becomes either 90 or 95 instead of the correct value of 85.</li></ol><h4>Isolation Levels and How They Address Read Phenomena</h4><p>To control these issues, database systems provide various isolation levels, each offering a trade-off between consistency and performance. These levels are:</p><ol><li><strong>Read Uncommitted</strong>:<br>• The lowest isolation level.<br>• Transactions can see uncommitted changes made by other transactions.<br>• Susceptible to dirty reads, non-repeatable reads, and phantom reads.</li><li><strong>Read Committed</strong>:<br>• Ensures that a transaction sees only committed changes.<br>• Eliminates dirty reads but allows non-repeatable reads and phantom reads.</li><li><strong>Repeatable Read</strong>:<br>• Guarantees that rows read during a transaction remain unchanged until the transaction completes.<br>• Prevents dirty reads and non-repeatable reads but does not eliminate phantom reads.</li><li><strong>Snapshot</strong>:<br>• Provides a “snapshot” of the database at the start of the transaction.<br>• Each query in the transaction sees a consistent view of the data as it was at the beginning.<br>• Prevents dirty reads, non-repeatable reads, and phantom reads effectively.</li><li><strong>Serializable</strong>:<br>• The highest isolation level.<br>• Transactions are executed in a manner equivalent to running them sequentially, one after the other.<br>• Ensures complete isolation but can lead to significant performance overhead.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gv99R4bsaIczcVH5mLxmrg.png" /><figcaption>Isolation Levels vs Read Phenomena, source: Wikipedia</figcaption></figure><h4>Database Implementations of Isolation</h4><p>The way a database management system (DBMS) enforces these isolation levels varies significantly. Broadly, they adopt one of two approaches:</p><ol><li><strong>Pessimistic Concurrency Control</strong>:<br>Uses locks (row-level, table-level, or page-level) to ensure no other transaction can modify or read the data until the lock is released.<br>Prevents lost updates effectively but can lead to deadlocks or reduced concurrency.</li><li><strong>Optimistic Concurrency Control</strong>:<br>Allows transactions to proceed without locking but tracks changes made.<br>If a conflict arises (e.g., another transaction modifies the data), the transaction fails or retries.</li></ol><blockquote>For example, in PostgreSQL:</blockquote><blockquote>“Repeatable Read” is implemented using a snapshot mechanism, avoiding phantom reads without locking. This implementation balances isolation and performance, making it efficient for read-heavy workloads.</blockquote><h4>The Trade-Offs of Isolation</h4><p>The choice of the appropriate isolation level depends on the application’s requirements:</p><ul><li><strong>Performance vs. Consistency</strong>: Higher isolation levels, such as Serializable, allow more consistency but at a cost to performance because of less concurrency.</li><li><strong>Workload Characteristics</strong>: Read-heavy applications might benefit from Snapshot isolation, while write-heavy workloads could opt for Repeatable Read or Read Committed.</li></ul><p>Each DBMS optimizes these levels differently, so understanding the underlying implementation is key to making informed decisions.</p><p>Isolation is not just a theoretical concept but a practical necessity for ensuring data integrity in concurrent environments. While it is easy to overlook, mastering it can significantly enhance the reliability and robustness of your applications.</p><p>Stay tuned for a deeper dive into topics like locks and advanced concurrency control mechanisms in future articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f57f6a91c72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Atomicity in Databases: The Indivisible Nature of Transactions]]></title>
            <link>https://medium.com/@mohannad.a.karim/understanding-atomicity-in-databases-the-indivisible-nature-of-transactions-7d79f92c930c?source=rss-e6a1580cdb7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d79f92c930c</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Mohannad A. Karim]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 17:26:12 GMT</pubDate>
            <atom:updated>2025-01-02T22:00:30.314Z</atom:updated>
            <content:encoded><![CDATA[<h4>In the realm of databases, ensuring the integrity and reliability of data is paramount. This is where the ACID properties — Atomicity, Consistency, Isolation, and Durability — come into play. Each of these properties plays a crucial role, but in this article, we will focus on the “A” in ACID: Atomicity. Let’s explore what atomicity is, why it’s critical, and how it operates in practice, supported by real-world examples.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8tPkTNZJGjEDsfnZDWJkg.jpeg" /><figcaption>Image from <a href="https://www.freepik.com/free-ai-image/online-cloud-data-storage-concept-cloudscape-digital-online-server-global-network-business-web-database-backup-computer-private-infrastructure-technology_40583100.htm#fromView=search&amp;page=1&amp;position=4&amp;uuid=aa68877a-21c7-46d7-be38-9f0810f6144a&amp;new_detail=true">FREEPIK</a></figcaption></figure><h3>What is Atomicity?</h3><p>Atomicity is a fundamental property of database systems that ensures transactions are treated as a single, indivisible unit. In essence, a transaction — a sequence of one or more database operations — must either be <strong>fully completed</strong> or <strong>entirely aborted</strong>. There is no middle ground.</p><p>This property is analogous to the behavior of an atom in physics: it is indivisible under normal circumstances. If any part of a transaction fails, atomicity guarantees that the database will revert to its state before the transaction began. In other words:</p><ul><li><strong>All queries in a transaction must succeed</strong> for the transaction to be committed.</li><li>If <strong>one query fails</strong>, all previously successful operations within the transaction will be rolled back.</li><li>If the system crashes or the database goes down before the transaction is committed, all changes made by the transaction are discarded.</li></ul><p>By adhering to this principle, atomicity ensures data integrity even in the face of failures.</p><h3>Why is Atomicity Critical?</h3><p>The importance of atomicity lies in its role in maintaining data consistency and reliability. Imagine a database transaction as a set of interconnected operations that depend on one another. Without atomicity, partial completion of a transaction could leave the database in an inconsistent state, causing cascading failures or corrupt data.</p><p>Atomicity also simplifies error handling for developers. By relying on the database to roll back changes automatically in case of failure, developers can focus on crafting robust applications without having to implement complex rollback mechanisms manually.</p><h3>Examples of Atomicity in Action</h3><h4>Example 1: Online Banking</h4><p>Consider a simple banking transaction where you want to transfer $100 from Account A to Account B. This transaction involves two steps:</p><ol><li>Deduct $100 from Account A.</li><li>Add $100 to Account B.</li></ol><p>SQL implementation:</p><pre>BEGIN TRANSACTION;<br><br>-- Step 1: Deduct $100 from Account A<br>UPDATE accounts<br>SET balance = balance - 100<br>WHERE account_id = &#39;A&#39;;<br><br>-- Step 2: Add $100 to Account B<br>UPDATE accounts<br>SET balance = balance + 100<br>WHERE account_id = &#39;B&#39;;<br><br>-- Commit the transaction if both steps succeed<br>COMMIT;<br><br>-- Rollback if any step fails<br>ROLLBACK;</pre><p>Atomicity ensures that both steps either succeed together or fail together. If the system crashes after deducting $100 from Account A but before adding it to Account B, the transaction will roll back, leaving both accounts unchanged. Without atomicity, the database could end up with $100 missing from Account A and no corresponding credit in Account B, resulting in financial discrepancies (data inconsistency).</p><h4>Example 2: E-Commerce Order Placement</h4><p>When a customer places an order on an e-commerce platform, several operations occur:</p><ol><li>Verify product availability.</li><li>Deduct the product quantity from inventory.</li><li>Charge the customer’s payment method.</li><li>Record the order details in the database.</li></ol><p>SQL implementation:</p><pre>BEGIN TRANSACTION;<br><br>-- Step 1: Verify product availability (optional check for illustration)<br>SELECT stock<br>FROM inventory<br>WHERE product_id = &#39;P123&#39;;<br><br>-- Step 2: Deduct the product quantity from inventory<br>UPDATE inventory<br>SET stock = stock - 1<br>WHERE product_id = &#39;P123&#39;;<br><br>-- Step 3: Charge the customer (simplified for illustration)<br>INSERT INTO payments (customer_id, amount, status)<br>VALUES (&#39;C456&#39;, 49.99, &#39;Pending&#39;);<br><br>-- Step 4: Record the order details<br>INSERT INTO orders (order_id, customer_id, product_id, quantity, status)<br>VALUES (&#39;O789&#39;, &#39;C456&#39;, &#39;P123&#39;, 1, &#39;Confirmed&#39;);<br><br>-- Commit the transaction if all steps succeed<br>COMMIT;<br><br>-- Rollback if any step fails<br>ROLLBACK;</pre><p>If any step fails — for instance, if the payment method is declined — atomicity ensures that all prior successful operations are rolled back. The product quantity is restored in the inventory, and no incomplete order record is left in the database.</p><h4>Example 3: Database Crash During a Transaction</h4><p>Suppose a database is processing a transaction that updates multiple rows in a table. Before the transaction can be committed, the database server unexpectedly crashes. Atomicity guarantees that none of the changes made by the transaction will persist. When the database is restarted, it will revert to the state it was in before the transaction began.</p><h3>How Atomicity is Achieved</h3><p>Modern database management systems (DBMS) use various mechanisms to enforce atomicity:</p><ol><li><strong>Transaction Logs</strong>: The DBMS maintains logs of all operations performed during a transaction. If a failure occurs, the log is used to identify and undo any changes made by the incomplete transaction.</li><li><strong>Undo Mechanisms</strong>: Many DBMSs implement undo logs that record the previous state of data before it is modified. In case of a rollback, the undo log is used to restore the original state.</li><li><strong>Write-Ahead Logging (WAL)</strong>: Before making any changes to the database, the DBMS writes details of the changes to a log. This ensures that if a failure occurs, the log can be used to roll back incomplete transactions.</li><li><strong>Two-Phase Commit Protocol</strong>: In distributed systems, the two-phase commit protocol ensures atomicity across multiple databases. It involves a preparation phase where all participating systems agree to commit, followed by a commit phase where changes are finalized.</li></ol><h3>Conclusion</h3><p>Atomicity is a cornerstone of database reliability, ensuring that transactions are completed as a whole or not at all. By treating transactions as indivisible units, atomicity safeguards data integrity, simplifies error handling, and enhances the robustness of database systems.</p><p>Whether you’re managing financial transactions, inventory systems, or any other critical application, understanding and leveraging atomicity is essential for building systems you can trust. By implementing atomicity, you’re not just preserving data consistency — you’re also laying the foundation for a resilient and dependable database architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d79f92c930c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Database Transactions]]></title>
            <link>https://medium.com/@mohannad.a.karim/understanding-database-transactions-ba672cad22f8?source=rss-e6a1580cdb7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba672cad22f8</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Mohannad A. Karim]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 15:27:59 GMT</pubDate>
            <atom:updated>2025-01-02T22:01:20.294Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ever wondered what ensures your bank transfer either completes fully or not at all? That’s the magic of database transactions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8tPkTNZJGjEDsfnZDWJkg.jpeg" /><figcaption>Image from <a href="https://www.freepik.com/free-ai-image/online-cloud-data-storage-concept-cloudscape-digital-online-server-global-network-business-web-database-backup-computer-private-infrastructure-technology_40583100.htm#fromView=search&amp;page=1&amp;position=4&amp;uuid=d64aef5b-70ef-4682-bbf0-f2353d36b4b1&amp;new_detail=true">FREEPIK</a></figcaption></figure><h3>What is a Transaction?</h3><p>A transaction in a database is a sequence of operations performed as a single, indivisible unit of work. Transactions in databases provide a way of ensuring consistency and integrity and therefore enhance reliability.</p><p>E.g. Transferring money from a bank account to another, for instance, several queries might be carried out, including:</p><ol><li>Fetch the source account balance ( SELECT)</li><li>Deducting the amount from the source account (UPDATE)</li><li>Adding the amount to the target account balance (UPDATE)</li></ol><p>All of these steps have to occur as a group, in other words all are successful or none are; hence implement.</p><h3>Transaction Lifespan</h3><p>A typical transaction goes ahead to the subsequent steps:</p><ol><li><strong>Transaction BEGIN</strong>: The transaction starts, notifying the database to keep a record of changes made during this phase.</li><li><strong>Transaction COMMIT</strong>: If all operations succeeded, and the transaction committed. Changes will be persisted to the disk.</li><li><strong>Transaction ROLLBACK</strong>: If there is an error, the transaction is cancelled, and all changes are undone.</li><li><strong>Unexpected Termination</strong>: If, due to an error or crash, the transaction is aborted, the database engine automatically starts a rollback process to ensure consistency.</li></ol><p>Modern database engines all do various optimisations to take advantage of specific aspects of the transaction management. For example, PostgreSQL is famous for extremely fast commit processing. However, one of the hardest scenarios is an eventual crash occurring during the commit phase. Quicker commits make that less likely to happen, which gives a very good reason to avoid extremely large transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*3NwXGLEuu1SV-EeF.png" /><figcaption>State transition diagram for a database transaction, source: DbVisualizer</figcaption></figure><h3>The Nature of Transactions</h3><h4>Data Modification Transactions</h4><p>Transactions are used mainly for changing and updating data. For instance, inserting a new record in one table and changing some related records in other tables usually comprise a single transaction.</p><h4>Read-Only Transactions</h4><p>It is very normal for an application to have transactions that do not alter data. These are known as read-only transactions, and the database optimises them for performance. A typical example is report generation based on a consistent view of the database as it existed at the start of the transaction. Declaring a transaction as read-only ensures the database focuses its efforts on providing consistent data without the overhead of tracking changes.</p><blockquote><em>Note: We will delve deeper into these concepts, including transaction isolation levels, in a future article.</em></blockquote><h3>Example of a Transaction</h3><p>Consider a traditional scenario where money is transferred from one account to another. This transaction might involve the following steps:</p><ol><li><strong>Check Source Account Balance</strong>: Ensure the source account has sufficient funds (SELECT).</li><li><strong>Deduct Amount from Source Account</strong>: Subtract the transfer amount from the source account (UPDATE).</li><li><strong>Add Amount to Target Account</strong>: Add the transfer amount to the target account (UPDATE).</li><li><strong>Record the Transaction</strong>: Insert a record of the transfer into the transactions table (INSERT).</li></ol><p><strong>SQL Queries for the Example</strong></p><pre>BEGIN TRANSACTION;<br><br>-- Step 1: Validate Sufficient Balance and Perform Operations<br>IF (SELECT balance FROM accounts WHERE account_id = 101) &gt;= 500 THEN<br><br>    -- Step 2: Deduct Amount from Source Account<br>    UPDATE accounts <br>    SET balance = balance - 500 <br>    WHERE account_id = 101;<br><br>    -- Step 3: Add Amount to Target Account<br>    UPDATE accounts <br>    SET balance = balance + 500 <br>    WHERE account_id = 202;<br><br>    -- Step 4: Record the Transaction<br>    INSERT INTO transactions (transaction_id, source_account, target_account, amount, transaction_date) <br>    VALUES (1, 101, 202, 500, CURRENT_TIMESTAMP);<br><br>    COMMIT;<br><br>ELSE<br>    -- Insufficient Funds<br>    ROLLBACK;<br>    RAISERROR(&#39;Insufficient funds in source account.&#39;, 16, 1);<br>END IF;</pre><p>If any step fails, a ROLLBACK will ensure all changes are undone:</p><pre>ROLLBACK;</pre><h3>Key Takeaways</h3><ul><li>The transaction is a set of queries considered as a single unit of work.</li><li>Transactions can modify the data and may also be read-only for particular use cases.</li><li>Even one query gets executed within implicit transactions, and commit happens immediately beneath the surface.</li><li>Good transaction management, like not making transactions too large, is a method to achieve system reliability and performance.</li></ul><p>Understanding transactions is a cornerstone of database development. In the future articles, we will explore the ACID principles and how they ensure data consistency in concurrent environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba672cad22f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>