<?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 Aziz Marzouki on Medium]]></title>
        <description><![CDATA[Stories by Aziz Marzouki on Medium]]></description>
        <link>https://medium.com/@azizmarzouki?source=rss-233f593038ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5e4ARJYaOkCJh5WkJHP1ww.jpeg</url>
            <title>Stories by Aziz Marzouki on Medium</title>
            <link>https://medium.com/@azizmarzouki?source=rss-233f593038ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 04:37:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@azizmarzouki/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[Empire of AI, Part 3: Power, and How Empires Fall]]></title>
            <link>https://medium.com/@azizmarzouki/empire-of-ai-part-3-power-and-how-empires-fall-7c5a560aadc4?source=rss-233f593038ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c5a560aadc4</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Aziz Marzouki]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 18:16:01 GMT</pubDate>
            <atom:updated>2026-10-21T18:16:01.891Z</atom:updated>
            <content:encoded><![CDATA[<h4>Five days that showed who really controls AI, what Karen Hao’s book gets right and wrong, and her answer to the question of what comes next.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y3HAX_PcAyVfRs81r-wnaA.png" /></figure><p>In Part 1, we saw how OpenAI’s mission grew from a nonprofit promise into what Karen Hao calls a formula for empire. In Part 2, we followed the supply chain down to the workers, the water and the power plants. This final essay comes back to the question underneath both: power. Who holds it in AI today, how did they get it, and could it be shared differently?</p><p>The best place to start is the moment when someone tried to take that power away and failed.</p><h3>Five Days in November</h3><p>On Friday, November 17, 2023, OpenAI’s board fired Sam Altman. The board then had six members. Four of them, the chief scientist Ilya Sutskever and three independent directors, Adam D’Angelo, Tasha McCauley and Helen Toner, voted him out. Their statement said he had not been consistently candid with them, which made it hard for the board to do its job. Greg Brockman, the company’s president and Altman’s close ally, was removed from the board too, and quit within hours.</p><p>What followed was chaos. Investors were furious. Microsoft, which had invested billions, learned about the decision only minutes before the public. Over the weekend, negotiations to bring Altman back broke down. On Monday, Microsoft announced that Altman and Brockman would lead a new AI team inside Microsoft. Almost all of OpenAI’s staff signed an open letter threatening to leave and follow them. Mira Murati, whom the board had made interim CEO, put her name first. Sutskever himself posted that he regretted his part.</p><p>On Tuesday night, November 21, the board gave in. Altman returned as CEO. Toner and McCauley left the board. D’Angelo stayed, and two new members joined: Bret Taylor, a former co-CEO of Salesforce, and Larry Summers, the former US treasury secretary. Altman agreed to an independent investigation. That night, employees flooded back into the office to celebrate. Someone turned on a smoke machine and set off the fire alarm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7943K67QckvNSbmPxP4mnA.png" /><figcaption>Figure 2 — On paper, the nonprofit board could fire the CEO. In practice, money, staff and partners decided the outcome. The right side shows the structure reported after OpenAI’s 2025 restructuring.</figcaption></figure><blockquote><em>The board had the legal power to fire the CEO. It did not have the practical power to make that decision stick.</em></blockquote><h3>What the Crisis Revealed</h3><p>Hao’s reading of the crisis is the key to the whole book. On paper, OpenAI was controlled by a nonprofit board whose only duty was to the mission, not to profit. That was the safeguard the founders had promised: if commercial pressure ever pulled the company away from its purpose, the board could step in.</p><p>The board stepped in, and the safeguard failed in five days. Hao argues this was not bad luck. By 2023, real power no longer sat with the board. It sat with the money, mainly Microsoft and the investors; with the staff, whose wealth depended on the company’s value and on a share sale that was underway; and with the CEO’s network of relationships across the industry. The board had authority. Everyone else had leverage.</p><p>Hao also describes, in detail, why the board acted. Senior people inside the company, she reports, had raised concerns over many months about Altman’s management: a pattern of telling different people different things, playing executives against each other, and keeping the board poorly informed. The board’s mistake, many people told her, was not explaining any of this publicly. Their silence let the story become one of a reckless board against a beloved leader.</p><p>For anyone who works on governance, in any company, this is the most useful lesson in the book. A safeguard is only as strong as the power behind it. A rule that no one can enforce is not a rule. It is a hope.</p><h3>The Omnicrisis</h3><p>If the board crisis showed who held power, the following year showed what happened when that power was no longer checked. Hao describes the spring of 2024 as a run of crises so dense that employees gave it a name: the Omnicrisis.</p><p>In May 2024, Sutskever left the company. So did Jan Leike, who co-led a team working on the long-term safety of advanced AI, saying publicly that safety had taken a back seat to shiny products. Days later, a Vox report revealed that departing employees were being asked to sign a lifelong agreement not to criticise the company, or risk losing their vested equity, often most of their wealth. Altman said he had not known and that the clause would not be enforced. Then the actress Scarlett Johansson released a statement objecting to a ChatGPT voice that sounded strikingly like her, after she had declined an offer to provide one. OpenAI said the voice belonged to a different actress and paused it.</p><p>Over the following months, more senior leaders left, including Murati in September. By the end of 2024, OpenAI was preparing a plan to change its structure and reduce the nonprofit’s control. That plan was later revised under public and legal pressure, but the direction was clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dYeBQ5Kz24Xww5zmQXQQw.png" /><figcaption>Figure 3 — A year of departures and controversies after the board crisis, as described in the book.</figcaption></figure><blockquote><em>When a check on power fails once, the next test is whether anyone builds a better one.</em></blockquote><h3>Three Kinds of Power</h3><p>In the epilogue, Hao steps back from OpenAI and offers a framework. Borrowing from the Stanford AI researcher Ria Kalluri, she says the AI empires control three kinds of power, and each one feeds the others.</p><p>The first is knowledge. By hiring the best researchers, closing their models to outside inspection and pulling away from open science, the big labs decide what is known about AI and who gets to know it. The second is resources: money, data, labor, chips, land, energy and water, which they gather at a scale no one else can match. The third is influence: the stories they tell about AGI, the dazzling product demos, and growing political access in Washington and other capitals.</p><p>The loop is what makes this powerful. Knowledge creates influence, because people trust the experts who built the thing. Influence attracts resources, because investors and governments want to back the winners. Resources buy more knowledge, because money hires talent and builds bigger models. Break into the loop anywhere, Hao suggests, and you can begin to weaken it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwqMZsizh_qGh8aLp0Ecww.png" /><figcaption>Figure 4 — Hao’s three axes of power. Each one strengthens the next, which is why the position of the leading labs is so hard to challenge.</figcaption></figure><blockquote><em>Power in AI is not one thing. It is a loop of knowledge, resources and influence, each one paying for the next.</em></blockquote><h3>A Different Way to Build AI</h3><p>Hao does not end with despair. She ends with a small radio station in New Zealand.</p><p>Te Hiku Media broadcasts in te reo Māori, the language of the Māori people, which colonial policy nearly destroyed. The station had decades of recordings, including elders whose accents carried the language as it was spoken before English took over. To make those recordings useful for learners, it needed transcriptions, and there were too few fluent speakers to do it by hand. So in 2016, the station’s leaders, Peter-Lucas Jones and Keoni Mahelona, decided to build a speech recognition model.</p><p>They set three conditions: consent, reciprocity and Māori sovereignty over the data. They asked the community and its elders first whether they wanted the project at all. They collected data only from people who understood how it would be used. They kept the data under their own care, licensing it only for uses the community agreed with. And they bought their own servers so they would not depend on a big tech cloud. As Mahelona puts it in the book, data is the last frontier of colonization.</p><p>The results are the book’s most hopeful numbers. In a ten-day community campaign, about 2,500 people donated around 200,000 recordings, giving 310 hours of transcribed audio. That was enough to train the first te reo speech model, with 86 percent accuracy, using two GPUs. For comparison, OpenAI trained its speech model, Whisper, on 680,000 hours of audio taken from the web.</p><p>The comparison is not perfectly fair. Whisper handles around a hundred languages and many tasks; Te Hiku’s model does one thing. But that is exactly Hao’s point. Not every problem needs a model that does everything. A small, focused model, built with consent and owned by the people it serves, can be good enough and far less costly to the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HU06I1zU_2aUDEMB42Pcng.png" /><figcaption>Figure 5 — OpenAI’s Whisper and Te Hiku Media’s te reo Māori model: two very different answers to the question of how AI should be built. Figures as reported in the book.</figcaption></figure><blockquote><em>The biggest model is not always the best answer. Sometimes the best answer is the one a community owns.</em></blockquote><h3>How Hao Thinks the Empire Falls</h3><p>From these examples, Hao builds her prescription, organised around the same three kinds of power.</p><p>To spread knowledge, she wants more public funding for research outside the big labs, independent testing of corporate models, and rules that make companies disclose what data they train on and how their systems are built. She points out that we inspect cars, medicines and household appliances, but have almost no comparable oversight of AI systems used by hundreds of millions of people. To spread resources, she wants stronger labor protections for data workers and for everyone whose work might be used as training data or automated away. She cites the Hollywood writers’ and actors’ strikes, which won limits on certain uses of AI, as proof that organised workers can push back. To spread influence, she wants broad public education about how AI really works, so that people can judge the claims made about it rather than simply trust them.</p><p>Running through all of it is a question she borrows from Kalluri, and it is the best idea in the book. Instead of asking whether a piece of AI is good, which everyone answers differently, ask whether it concentrates power or spreads it.</p><h3>What the Book Gets Right</h3><p>Across three essays, it is worth bringing the assessment together, in the same way we would for any influential book.</p><p>First, the reporting. With more than 300 interviews, internal documents and years on the beat, this is one of the most detailed accounts of a modern tech company ever published. Much of the inside story of OpenAI’s early years, and of the board crisis, is now part of the public record because of it.</p><p>Second, it makes hidden costs visible. Before books like this, the labor and physical resources behind AI were largely invisible to the public. They are now part of mainstream debate.</p><p>Third, it shows that scale was a choice, not destiny. By telling the history, Hao makes clear that the current path of ever-bigger models was a bet made by a few people, which means other paths are still possible.</p><p>Fourth, it offers a better question. Asking who gains and who loses power from a technology is useful for anyone, whether you are a policymaker, an investor or a developer.</p><h3>What the Book Gets Wrong or Oversimplifies</h3><p>The empire metaphor sometimes carries more weight than the evidence. It is a powerful lens, but applied to every decision, it can make ordinary business choices, like charging for a product or raising capital, look like conquest. The comparison with colonial violence also risks minimising what colonised people actually suffered, a point some critics have made.</p><p>The benefits of AI are underplayed. Hundreds of millions of people use these tools because they find them helpful, and some uses in science, medicine and accessibility are significant. The book mentions this but does not weigh it seriously against the costs, so its overall picture is tilted.</p><p>The account is one-sided by circumstance. OpenAI and Altman declined to take part, so their side mostly appears through public statements or through people who disagreed with them. That is not Hao’s fault, but readers should remember it, especially in the most personal passages about Altman.</p><p>And at least one major number was wrong. As discussed in Part 2, the comparison of a Chilean data center’s water use with a town’s consumption was overstated by about 1,000 times because of a unit error, which Hao corrected in late 2025. It does not undo the book’s argument, but it is a reminder that dramatic statistics need checking, from every side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEzqvoNESHVCTI-qwtoGqg.png" /><figcaption>Figure 6 — Weighing the book: deep reporting and an important question on one side; a stretched metaphor, a one-sided account and a corrected statistic on the other.</figcaption></figure><blockquote>Empire of AI<em> is an essential book about power and a weaker book about benefits. Read it for the questions, and check the numbers.</em></blockquote><h3>What the Book Means in 2026</h3><p>The book was finished in January 2025, and much has changed since. OpenAI completed its restructuring in late 2025. Its business became a for-profit public benefit corporation with no cap on investor returns, while the nonprofit, renamed the OpenAI Foundation, kept the right to appoint the board and a stake of about a quarter of the company. Microsoft holds a slightly larger stake. Supporters say the nonprofit’s role survived. Critics say a nonprofit that owns a minority stake in a company worth hundreds of billions is not a check on it; it is a shareholder.</p><p>The spending race has also grown. Plans for giant data centers that sounded extreme in the book are now being announced regularly across the industry. That makes Hao’s questions about energy, water and land more relevant, not less.</p><p>For readers in Europe, there are a few specific takeaways. The EU’s AI Act is now in force and is starting to require more transparency about training data and testing, close to some of what Hao calls for. Europe also has a choice about its own AI path: depend entirely on a few American labs, or support smaller, specialised and open models built closer to home. And for anyone building AI products, including in finance and other regulated industries, the book’s practical message is to know your supply chain: where your model’s data came from, who labelled it, and where it runs.</p><h3>The Better Question</h3><p><em>Empire of AI</em> is often read as an attack on OpenAI. It is better read as a book about how power works when a new technology arrives. A grand mission gathers talent and money. A bet on scale becomes an industry standard. Costs move outward to people with little voice. And when someone tries to apply the brakes, the people with the most leverage, not the people with formal authority, decide what happens.</p><p>None of that is unique to OpenAI, and none of it is inevitable. The Te Hiku story shows that a very different kind of AI is possible: small, consensual, owned by its community. Whether that kind of AI grows depends on choices that are still being made by regulators, companies, researchers and users.</p><p>So the question the book leaves us with is not whether AI is good or bad. That question has too many answers. A better one is quieter and more practical: does this system, this product, this company concentrate power or spread it? If more of us asked that before we built, bought or regulated AI, the empire would already be a little smaller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXFZReYrgCOSdPlPQL5IVw.png" /><figcaption>Figure 7 — Hao’s closing test for any AI system: does it concentrate power, or spread it?</figcaption></figure><h3>References and notes</h3><p><strong>Primary source.</strong> Karen Hao, <em>Empire of AI: Dreams and Nightmares in Sam Altman’s OpenAI</em> (Penguin Press, 2025), especially the chapters “The Gambit,” “Cloak-and-Dagger,” “Reckoning,” “A Formula for Empire” and the epilogue, “How the Empire Falls.”</p><p><strong>Later events.</strong> The October 2025 restructuring of OpenAI and the November 2025 correction of the book’s water figure are based on news reporting after the book’s publication.</p><p><strong>Disclaimer.</strong> This essay is for education and discussion. It summarises and comments on a published book. Statements about named people reflect the book’s reporting and are not established facts unless stated. All illustrations are original works created for this essay.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c5a560aadc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empire of AI, Part 2: The Hidden Costs]]></title>
            <link>https://medium.com/@azizmarzouki/empire-of-ai-part-2-the-hidden-costs-61f4daa46080?source=rss-233f593038ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/61f4daa46080</guid>
            <category><![CDATA[sustainability]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[labor]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ethics]]></category>
            <dc:creator><![CDATA[Aziz Marzouki]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 18:16:01 GMT</pubDate>
            <atom:updated>2026-10-20T18:16:01.734Z</atom:updated>
            <content:encoded><![CDATA[<h4>The data, the workers, the water and the energy behind every chatbot answer, and what Karen Hao’s reporting does and does not prove.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Go6aIFrKDK8LDkPKkve3Uw.png" /></figure><p>When you type a question into a chatbot, the answer seems to come from nowhere. There is a clean white box, a blinking cursor, and then fluent text. Nothing about the experience suggests a factory. That is exactly the impression Karen Hao wants to break.</p><p>In Part 1, we followed the mission: how OpenAI’s promise to benefit humanity became a way to gather talent, money and power. This essay follows the supply chain. Hao travelled to Kenya, Colombia, Chile and Uruguay, and the strongest chapters of <em>Empire of AI</em> are the ones set there. They describe the people and places that make AI possible but rarely appear in the story the industry tells about itself.</p><p>The argument of Part 2 is simple. AI is not weightless. It is built from human work and physical resources, and the costs of that work and those resources often land on people far from Silicon Valley, with little say and little benefit. Where the book is right about this, it is important. Where it overreaches, and in one well-known case it did, a careful reader should notice that too.</p><h3>AI Has a Supply Chain</h3><p>We are used to thinking about supply chains for physical products. A phone has mines, factories and shipping routes behind it. Hao’s point is that a large language model has one too.</p><p>It starts with data: books, news articles, forum posts, images, code and personal writing, collected from the internet in vast amounts, often without consent or payment. Then comes human labor: people who label data, rate answers and filter out the worst content so the model behaves well. Then come chips, which depend on minerals and a few specialised factories. Then data centers, huge buildings full of servers that need land, electricity and water for cooling. Only at the end of this chain is the friendly chat window.</p><p>A water activist in Uruguay, Daniel Pena, sums it up in the book: the energy comes from one place, the data goes to another, minerals come from somewhere else, and workers from somewhere else again. Each local community sees only its own piece. That is why the full cost is so hard to see, and so easy to ignore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIw_-4JNM9IwxmnNMP2RWQ.png" /><figcaption>Figure 2 — Every chatbot answer depends on a long chain of data, labor and physical infrastructure, spread across many countries.</figcaption></figure><blockquote><em>A chatbot looks like software. Underneath, it behaves like an industry.</em></blockquote><h3>Data as Raw Material</h3><p>The first resource is data, and the scaling strategy from Part 1 makes it endless. If bigger models are better, you always need more text, more images, more audio. Hao describes how standards fell as the hunger grew. Early on, researchers cared about the quality of training data. Later, the priority was quantity, and the filtering got weaker.</p><p>This has two consequences. The first is about rights. Writers, artists and news organisations found their work used to train systems that now compete with them, without being asked or paid. Many of the lawsuits against AI companies come from this. The second is about quality. When you take in the whole internet, you take in its worst parts too: hate, violence and abuse. Hao notes that a large open image dataset used to train image generators was later found to contain child sexual abuse material.</p><p>Someone has to clean that up. That brings us to the people.</p><h3>The Workers in Kenya</h3><p>In late 2021, OpenAI worked with Sama, an outsourcing firm in Nairobi, to build a filter that could detect harmful content. To teach the filter, humans had to read and sort huge numbers of disturbing texts: descriptions of violence, abuse and sexual content involving children. The book reports that workers earned on average between $1.46 and $3.74 an hour. Most did not know who the client was or why they were doing the work, because of confidentiality rules common in the industry.</p><p>Hao met four of these workers in 2023 for a front-page story in The Wall Street Journal. One of them, Mophat Okinyi, was on the team handling sexual content. She describes how the work damaged his mental health and his closest relationships. There is a painful twist: the technology he helped make safe would go on to erode the job prospects of his own brother. The contract ended abruptly in early 2022. Okinyi later became an organiser with a union for African content moderators and co-founded a nonprofit to support tech workers.</p><p>Sama disputes some of the workers’ claims. But the basic picture, low pay for traumatic work hidden behind non-disclosure agreements, is supported by several investigations, starting with reporting by Time magazine in early 2023.</p><h3>The Workers in Venezuela</h3><p>The second story is about data labelling platforms, and it is just as revealing. When Venezuela’s economy collapsed, highly educated people found themselves desperate for any income in US dollars. Data labelling companies noticed. The book describes how Scale AI, a major supplier to AI labs, saw a surge of sign-ups from Venezuela on its worker platform, Remotasks, and began recruiting there actively. A former employee explains the reason bluntly: Venezuelans were the cheapest workers available.</p><p>Hao calls this disaster capitalism: finding a population in crisis and using its desperation to lower costs. She tells it through Oskarina Fuentes, a Venezuelan who fled to Colombia and kept working on labelling platforms. Tasks arrived without warning and disappeared in seconds as thousands of workers competed for them. Once, a task worth enough to live on for a month arrived while she was out walking; she ran home and lost it. After that, she stopped leaving the house on weekdays. Today, the book says, she works across five platforms at once, tasks pay between one and five cents each, and she earns about $335 a month.</p><p>The contrast Hao draws at the end of the book is striking. A research project called the Data Workers’ Inquiry paid participating data workers the standard German researcher rate of €25 an hour. Its founder asks the obvious question: if this work produces billions in revenue, why do we ask how little workers will accept instead of how much companies can afford?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3u6bM52tesTl2rgD5LHaQ.png" /><figcaption>Figure 3 — Reported hourly pay for content moderation in Kenya, compared with the rate a research project chose to pay data workers. Figures as reported in the book.</figcaption></figure><blockquote><em>The cleaner and safer a chatbot feels, the more invisible work went into making it that way.</em></blockquote><h3>The Machines Need Power</h3><p>The scaling bet does not only need data and people. It needs computing power on a scale that is hard to picture, and computing power needs electricity.</p><p>Hao gives a sense of the size. Until recently, the largest data centers were built for around 150 megawatts, which she says is about as much energy in a year as 122,000 American homes. Companies are now planning AI campuses of 1,000 to 2,000 megawatts, each using as much energy as one and a half to three and a half cities the size of San Francisco. The book reports that Microsoft and OpenAI sketched a supercomputer project, internally called Stargate, costing around $100 billion and possibly needing up to 5,000 megawatts, close to the average demand of New York City.</p><p>The problem is that few places can supply that much power to one site. Utilities are building new power plants, and in some places that means more gas and delayed closures of fossil fuel plants. An OpenAI employee quoted in the book puts it plainly: they were running out of land and power. This is where the digital empire becomes a physical one, in Hao’s framing: to grow, it needs territory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4ZIG8LvxTn3JuZ7JLHrLw.png" /><figcaption>Figure 4 — From large data centers to planned AI megacampuses. Estimates as reported in the book, based on 2024 plans.</figcaption></figure><blockquote><em>The cloud is not in the sky. It is in a building, on land, connected to a power plant.</em></blockquote><h3>Water in a Drought</h3><p>Data centers also need water, mostly to keep servers cool. The book’s chapter on Chile and Uruguay is about what happens when that need meets a drought.</p><p>In Chile, Google planned a data center in Cerrillos, a working-class area near Santiago with a painful history of industrial pollution. A local water activist group, MOSACAT, read the company’s 347-page environmental filing and found that the facility could use an estimated 169 liters of drinking water per second for cooling. In a country in the middle of a long drought, the group fought back. In 2024, Chile’s environmental court ruled that Google could not build a water-using data center there; Google says it plans an air-cooled design instead. In Uruguay, Google planned a data center during a drought so severe that the capital, Montevideo, began mixing salty water into its drinking supply. Daniel Pena, the activist quoted earlier, petitioned the government for a proper study; he says the approval went ahead quietly.</p><p>These stories are real and important. But this is also where the book made its biggest factual mistake, and it is worth being clear about it. To help readers understand the 169 liters per second, the book compared it with the water used by the people of Cerrillos and said the data center could use more than a thousand times as much. In November 2025, after independent analysts checked the numbers, Hao acknowledged that the figure for the town’s water use came from a government document that appears to have used the wrong unit. The comparison was off by about 1,000 times. The data center’s planned use was still large for a community in drought, but roughly comparable to the town’s residential use, not a thousand times larger.</p><p>How should a reader treat this? Two things are true at once. Hao corrected the error publicly, which is what good journalists do. And the error was repeated widely, which shows how easily one dramatic number can shape a debate. The safest lesson is to trust the local stories, which are well reported, and to check any single comparison before repeating it. That applies to every side of the AI debate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcTipjrj2AP0CFQMmUynQA.png" /><figcaption>Figure 5 — The book’s original comparison and the corrected picture. The planned water use was still significant in a drought, but the gap with the town was far smaller than first reported.</figcaption></figure><blockquote><em>The local fights over water are real. The most quoted number about them was wrong. A careful reader can hold both facts.</em></blockquote><h3>The Languages Left Behind</h3><p>The last hidden cost is cultural, and it is one many readers will not have considered. Large language models need huge amounts of text. Only a few languages have that much text online.</p><p>The book’s figures are sobering. More than seven thousand languages are still spoken. About half are endangered, according to UNESCO. Around a third have some online presence. Fewer than 2 percent are supported by Google Translate. And according to OpenAI’s own testing, only fifteen languages, about 0.2 percent, were handled by GPT-4 with above 80 percent accuracy.</p><p>As AI tools become part of daily life, from customer service to schoolwork, speakers of smaller languages face a choice: switch to a dominant language like English, or be left out. Hao argues that this speeds up the loss of languages that were already under pressure from colonial history. For a European reader, the point is not abstract. Many smaller European languages face the same risk on a smaller scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ILpn7f95pJ3A5AggvH1qg.png" /><figcaption>Figure 6 — Of the world’s 7,000+ languages, only a tiny share is well served by today’s largest models. Figures as reported in the book.</figcaption></figure><blockquote><em>When a technology speaks only a few languages, it quietly decides whose knowledge counts.</em></blockquote><h3>What Part 2 Gets Right, and Where to Be Careful</h3><p>The great strength of these chapters is that they make the invisible visible. Before reports like Hao’s, most users had no idea that chatbots were trained with the help of low-paid workers reading horrifying content, or that data centers were competing with towns for water. That knowledge is now part of the public debate, and Hao is one of the main reasons why.</p><p>There are also limits. The environmental numbers in the book are estimates, many based on plans rather than measured use, and the industry changes quickly. Some companies have since moved toward cooling systems that use less water, and the energy picture depends heavily on where the power comes from. The labor stories are vivid but come from a limited number of workers and places; they show what can happen, not necessarily what always happens. And the book does not weigh these costs against the benefits AI brings, which a full assessment would need to do.</p><p>None of this cancels the core point. AI has real material costs, those costs are not shared evenly, and the people who bear them rarely have a voice in the decisions. That is a reasonable thing to want fixed, whatever you think of the empire metaphor.</p><h3>What This Means for the Rest of Us</h3><p>For people who build or buy AI, which today includes most companies, these chapters suggest a few practical questions. Where does a vendor’s training data come from, and was it licensed? Who labels their data, and under what conditions? Where are their data centers, and how are they powered and cooled? Few vendors answer these questions well today, but asking them is how standards begin. In Europe, rules such as the AI Act are starting to require more transparency about training data, and supply-chain due diligence rules are pushing companies to look at labor conditions further down the chain.</p><p>For ordinary users, the lesson is not to stop using AI. It is to stop thinking of it as free and weightless. Every answer has a cost. Most of it is paid by someone you will never meet.</p><p>In Part 3, we return to the center of power: the five days in November 2023 when OpenAI’s board tried to remove its CEO and failed, what that crisis revealed about who really controls AI, and Hao’s proposal for how the empire could be taken apart.</p><h3>References and notes</h3><p><strong>Primary source.</strong> Karen Hao, <em>Empire of AI: Dreams and Nightmares in Sam Altman’s OpenAI</em> (Penguin Press, 2025), especially the chapters “Disaster Capitalism,” “Plundered Earth” and the epilogue.</p><p><strong>Correction on water figures.</strong> In November 2025, Karen Hao publicly acknowledged that the book’s comparison between the planned Cerrillos data center and the town’s water use was overstated by roughly 1,000 times, due to a unit error in a source document. This essay uses the corrected framing.</p><p><strong>Disclaimer.</strong> This essay is for education and discussion. Figures are as reported in the book unless stated otherwise and many are estimates. All illustrations are original works created for this essay.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61f4daa46080" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empire of AI, Part 1: The Mission That Built an Empire]]></title>
            <link>https://medium.com/@azizmarzouki/empire-of-ai-part-1-the-mission-that-built-an-empire-5ea335ef7523?source=rss-233f593038ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ea335ef7523</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ethics]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Aziz Marzouki]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 18:16:01 GMT</pubDate>
            <atom:updated>2026-10-19T18:16:01.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>How a nonprofit promise to “benefit all of humanity” became one of the most powerful companies on earth, and what Karen Hao’s book says about how it happened.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNukh3qs7IQr_xW0PqKXOg.png" /></figure><p>On a Friday in November 2023, the most famous CEO in technology logged on to a video call and learned he had been fired. Sam Altman was in a Las Vegas hotel for a Formula One race. Four of his board members told him the news in a few sentences. Within minutes, the world read that the board no longer trusted him to lead OpenAI. Five days later, he was back in charge, and most of the people who had fired him were gone.</p><p>That scene opens Karen Hao’s <em>Empire of AI</em>, and it is a smart place to start. The firing looked like a strange piece of boardroom drama. Hao argues it was something larger: the moment when a fight that had been running inside OpenAI for eight years broke into public view. On one side was the promise the company was founded on. On the other was the money, the power and the speed that the promise had made possible.</p><p>Hao is an unusual guide. She first covered OpenAI in 2019 for MIT Technology Review, when it was still a small research lab, and she has reported on it since. The book is built on more than 300 interviews with around 260 people, including over 90 current and former OpenAI staff. OpenAI and Altman chose not to take part. That matters, and we will come back to it.</p><p>This is the first of three essays on the book. This one is about the mission: where it came from, how it changed, and why Hao believes it became, in her words, a formula for empire. The second essay looks at the hidden costs, the workers, water and energy behind the chatbot. The third looks at power: the board crisis, what the book gets right and wrong, and Hao’s idea of how such empires fall.</p><h3>Why “Empire”?</h3><p>The title is a deliberate provocation. Hao says she tried many metaphors over years of reporting and found only one that fit: empire.</p><p>Her argument runs like this. Colonial empires took resources that were not theirs, used cheap or forced labor to extract them, and told a story about bringing progress and civilization to justify it all. They also claimed they had to grow, because rival empires would grow if they did not. The result was enormous wealth at the center and heavy costs everywhere else.</p><p>The AI giants, Hao says, follow the same logic without the open violence. They take the writing, art and personal data of billions of people to train their models, mostly without asking or paying. They need land, electricity and water for vast data centers. They rely on low-paid workers, often in poorer countries, to clean and label data. And they tell a story of their own: that this is the road to a better future for everyone, and that if they slow down, a worse rival, usually China, will win.</p><p>It is a strong frame, and a reader should hold it carefully. A metaphor highlights some things and hides others. Calling a software company an empire makes the pattern of extraction easy to see. It also risks making every business decision look sinister, and it says less about the real benefits people get from these tools. Read the book with both ideas in mind: the metaphor is a lens, not a verdict.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtZf7xu2vZtUtOpFEuR1gg.png" /><figcaption>Figure 2 — Hao’s central metaphor: the AI giants do not repeat the violence of colonial empires, but they repeat the logic of taking resources, using cheap labor and telling a story of progress.</figcaption></figure><blockquote><em>The empire metaphor is not about brutality. It is about a pattern: take what you need, pay little for it, and call it progress.</em></blockquote><h3>A Dinner in 2015</h3><p>OpenAI began, like many Silicon Valley stories, at an expensive dinner. In the summer of 2015, Altman, then president of the startup accelerator Y Combinator, invited a group of engineers and researchers to a private room at a luxury hotel near Stanford. Elon Musk arrived over an hour late. Among the guests were Greg Brockman, a star engineer from Stripe, and Ilya Sutskever, a young researcher at Google who had helped start the deep learning boom.</p><p>Musk had become obsessed with the idea that AI could one day be more intelligent than humans and threaten humanity. He was especially worried that Google, which had just bought the London lab DeepMind, would control that future. The group’s answer was a new kind of lab. It would be a nonprofit. It would share its research openly. It would build artificial general intelligence, or AGI, a machine as capable as a human at most tasks, for the benefit of all of humanity and not for shareholders. Musk, Altman and others pledged $1 billion.</p><p>Hao is careful to show that the nonprofit choice was partly about image. The founders knew public perception mattered and that openness would help them recruit researchers from Google and others who could pay far more. The mission was sincere for many people. It was also useful.</p><p>That tension, between a mission people believed in and a mission that helped win a competition, runs through the whole book.</p><h3>From Open to Closed</h3><p>The first big turn came quickly. Within a year or two, the leaders realized that their approach to AI needed far more computing power than a nonprofit could pay for. Musk tried to take control and fold the lab into Tesla. When that failed, he left, and much of the promised money never arrived.</p><p>In 2019, OpenAI made three moves in a row that Hao saw up close. First, it announced a language model called GPT-2 and said it was too dangerous to release in full, a decision many researchers saw as a publicity stunt. Second, Altman became CEO and OpenAI created a new “capped-profit” company under the nonprofit. Early investors could earn up to 100 times their money; a critic online pointed out that this meant $10 million could become $1 billion before any cap applied. Third, Microsoft invested $1 billion and got priority access to commercialize OpenAI’s technology, with OpenAI using Microsoft’s cloud.</p><p>Hao visited the office that August for her first profile. She found a company that still talked about openness but had become secretive, and leaders who struggled to explain what AGI was or how they would know they had built it. When the profile ran, the company was unhappy. Hao describes years of strained relations that followed.</p><p>From there, the shifts kept coming. In 2020, instead of releasing GPT-3, OpenAI sold access through an API, and described that as its new form of openness. In 2022, it raced ChatGPT out the door. By 2024, Altman described part of the mission as putting powerful tools in people’s hands “for free (or at a great price).” Each step was explained as a way of serving the same mission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e9gYYqJCSve_iME323iKaQ.png" /><figcaption>Figure 3 — The same mission statement, read a new way almost every two years. The 2015–2024 steps come from the book. The 2025 step comes from later reporting: OpenAI’s business became a for-profit public benefit corporation, still overseen by a nonprofit foundation.</figcaption></figure><blockquote><em>OpenAI rarely abandoned its mission. It reinterpreted it. That is harder to see, and harder to resist.</em></blockquote><h3>The Religion of Scale</h3><p>If one idea built OpenAI, it is scale. Hao credits Sutskever with the core belief. Neural networks, he argued, are rough copies of brains, and bigger brains are smarter. So you do not need clever new methods. You need bigger models, more data and more computing power. “Success is guaranteed,” he liked to say.</p><p>In 2018, OpenAI researchers measured how much computing power the biggest AI breakthroughs had used since 2012. They found it had doubled every 3.4 months, far faster than the famous Moore’s Law for computer chips, which doubles roughly every two years. Over six years, that was an increase of about 300,000 times. Brockman began calling it OpenAI’s Law. The leadership decided they had to keep up with that curve, or fall behind.</p><p>This choice, Hao argues, is the root of almost everything else in the book. Once you believe scale is the path, you need enormous amounts of three things: money, data and physical infrastructure. Money pushed OpenAI toward Microsoft and away from the nonprofit model. Data pushed it to scrape ever more of the internet, including copyrighted books and art. Infrastructure pushed it toward giant data centers that need land, power and water.</p><p>She also makes a point that is easy to miss. Scale was not the only path to better AI. It was a choice. Other approaches, using less data and smaller models, were possible, and some researchers argued for them. But once OpenAI showed what scale could do with ChatGPT, the whole industry copied it. Independent research shrank, because few universities or small labs can afford the computing bills. A bet made by one lab became the rule for the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZZM6th2xNCeBICBOnvMww.png" /><figcaption>Figure 4 — Computing power used by top AI systems grew far faster than chip performance. The lines show the shape of the trend on a log scale, not exact data points.</figcaption></figure><blockquote><em>Scale was a hypothesis that became a strategy, and then a strategy that became an industry.</em></blockquote><h3>Boomers and Doomers</h3><p>One of the book’s most useful contributions is its map of the beliefs inside AI. Hao describes two camps that grew up around OpenAI.</p><p>The first she calls the Doomers. Many came from the effective altruism movement. They believe advanced AI could become uncontrollable and might even end humanity. They want to slow down, test carefully, and keep the most powerful systems in safe hands. The second she calls the Boomers. They see AI as progress, sometimes as a moral duty, and want to build and release it as fast as possible.</p><p>Inside OpenAI, these camps fought for years. Hao describes how a group focused on safety, led by Dario Amodei, left in 2020 and 2021 to found Anthropic. Some people came to see Anthropic as the Doomer company and OpenAI as the Boomer one. Others saw OpenAI itself as the battlefield. Sutskever, who grew more spiritual about AGI over time, would lead staff in a chant at company events: “Feel the AGI.”</p><p>Hao’s sharpest point is what the two camps share. Both assume AGI is coming and that it will be extremely powerful. Both conclude that a small group of experts must therefore control it, either to make it safe or to make it fast. Neither camp spends much time on the harms happening today, to workers, artists, local communities and the environment. Those, as we will see in Part 2, are what Hao cares about most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73riHrgYValrMxytFpJybA.png" /><figcaption>Figure 5 — The debate inside AI often looks like a fight between safety and speed. Hao argues both sides agree on the deeper premise: that AGI is near and must be controlled by a few.</figcaption></figure><blockquote><em>The loudest debate in AI is about how fast to build. The quieter question is who gets to decide.</em></blockquote><h3>The Man at the Center</h3><p>Hao’s portrait of Altman is the part of the book most readers will talk about, and the part to read most carefully. She describes a brilliant fundraiser and dealmaker, warm in person and very good at telling people what they want to hear. Many sources describe a pattern of saying different things to different people. That pattern, she argues, is what eventually led the board to say he had not been “consistently candid.”</p><p>She also includes difficult personal material, including serious allegations made by his sister, which Altman and his family have denied. A careful reader should separate two kinds of claims. Some are well documented, with emails, lawsuits and many sources. Others are personal and contested. The book’s argument about OpenAI’s power does not depend on the second kind.</p><p>One detail stays with you. Altman once said the best book he read in a year was a collection of Napoleon’s thoughts. What struck him was how Napoleon took the French Revolution’s motto of liberty, equality and fraternity, and used it to build a system of control. Hao places that comment at the start of her closing chapter, and the parallel is clear: a beautiful slogan can be reused to justify its opposite.</p><h3>The Formula for Empire</h3><p>Hao’s main conclusion about the mission is that it started as idealism and became a tool. She says the mission works in three ways.</p><p>First, it attracts talent. A grand goal, saving or transforming humanity, pulls the best researchers away from bigger salaries. Altman wrote in 2013 that the most successful founders set out to create something closer to a religion than a company. Second, it attracts capital and pushes aside rules. If you are building the future and racing dangerous rivals, who wants to slow you down with regulation? Third, and most important, it is vague. No one can say exactly what AGI is, or what “benefit all of humanity” means. So the mission can be reinterpreted to justify whatever the company needs next. Two days before he was fired, Altman himself called AGI a ridiculous and meaningless term.</p><p>The third ingredient is the clever one. A clear goal can be measured and held to account. A vague goal cannot. You can never show that a company has failed a mission no one has defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdqNlqnB5WMQK8GmCtgz5w.png" /><figcaption>Figure 6 — Hao’s formula: a mission that gathers talent, a mission that gathers capital, and a mission vague enough to mean whatever is needed.</figcaption></figure><blockquote><em>A goal no one can define is a goal no one can hold you to.</em></blockquote><h3>What Part 1 Leaves Us With</h3><p>It is worth pausing here to be fair. Hao’s history is detailed and well sourced, and much of it has since been supported by court filings and other reporting. But it is told from one side. OpenAI did not cooperate, so its leaders’ reasons often come through the eyes of people who left or disagreed with them. Some readers will feel that decisions which look cynical in the book, such as the turn to profit, were also practical answers to a real problem: building frontier AI is extremely expensive.</p><p>The book also says less about why people use these tools. Hundreds of millions of people use ChatGPT because it helps them write, learn, code and think. Hao does not deny this, but it is not her focus, and a reader should keep it in view.</p><p>What Part 1 does very well is show how a mission works inside a company. It is not just a line on a website. It decides who joins, who funds you, and which choices feel justified. When that mission is grand and vague, it can carry a company a very long way from where it started.</p><p>Since the book was finished, the story has moved again. In late 2025, OpenAI completed a restructuring that turned its business into a for-profit public benefit corporation. The nonprofit, renamed the OpenAI Foundation, kept the power to appoint the board and a stake of about a quarter of the company, with Microsoft holding a slightly larger share. Supporters call this a sensible balance. Critics call it the final step away from the 2015 promise. Either way, it fits the pattern Hao describes: the mission stayed, and its meaning changed.</p><p>In Part 2, we leave the boardroom and follow the supply chain: the data workers in Kenya and Venezuela, the data centers in Chile and Uruguay, and the energy and water that sit under every answer a chatbot gives.</p><h3>References and notes</h3><p><strong>Primary source.</strong> Karen Hao, <em>Empire of AI: Dreams and Nightmares in Sam Altman’s OpenAI</em> (Penguin Press, 2025).</p><p><strong>Later events.</strong> The 2025 restructuring of OpenAI into a public benefit corporation overseen by the OpenAI Foundation is based on news reporting from October and November 2025, not on the book.</p><p><strong>Disclaimer.</strong> This essay is for education and discussion. It summarises and comments on a published book. Claims about people and companies are the author’s reporting as presented in the book, not established facts unless stated. All illustrations are original works created for this essay.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ea335ef7523" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rich Dad Poor Dad: The Money Lessons That Changed How We Think About Wealth]]></title>
            <link>https://medium.com/@azizmarzouki/rich-dad-poor-dad-the-money-lessons-that-changed-how-we-think-about-wealth-168d9db48ff5?source=rss-233f593038ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/168d9db48ff5</guid>
            <category><![CDATA[money]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[personal-finance]]></category>
            <category><![CDATA[book-review]]></category>
            <category><![CDATA[financial-freedom]]></category>
            <dc:creator><![CDATA[Aziz Marzouki]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 16:29:19 GMT</pubDate>
            <atom:updated>2026-10-05T16:29:19.727Z</atom:updated>
            <content:encoded><![CDATA[<h4>What Robert Kiyosaki got right, what he oversimplified, and what his ideas mean in 2026.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScklE_X4rd0eM14L7fqYzQ.png" /></figure><p>Few personal finance books have been praised, quoted, mocked and gifted as often as Rich Dad Poor Dad. Robert Kiyosaki self-published it in 1997, with the accountant Sharon Lechter as co-author, and expected it to sell modestly at seminars. Instead it became one of the best-selling money books ever written, translated into dozens of languages and passed from parents to children like a family recipe. Nearly thirty years later it still sits on airport shelves next to books written last month.</p><p>The book’s staying power is odd when you look at what is actually inside it. There are no spreadsheets, no asset allocation tables and almost no data. It is a short, anecdotal story about a boy growing up in Hawaii with two father figures who disagreed about money. Many of its claims are exaggerated. Some are wrong. Several of its examples belong to a tax system most readers will never live under.</p><p>And yet people keep reading it, because it does one thing better than most finance books: it changes the question. Most money advice asks how to earn more or how to spend less. Kiyosaki asks where your money goes after it arrives, who it works for, and whether the things you own are feeding you or eating you. That shift is the real subject of the book. It is less a manual for getting rich than a lesson in how to think about money.</p><p>This essay summarises the book’s main arguments, explains the financial ideas underneath them, and then does what the book rarely does: it checks them. Where Kiyosaki is right, we say so. Where he is selling a story, we say that too. And because the world of 1997 is not the world of 2026, we ask what his framework means for someone building a financial life today, in Europe, with index funds, software and AI in the picture.</p><h3>Two Dads, Two Financial Operating Systems</h3><p>The book is built on a simple device. Young Robert has two dads. His biological father, the “poor dad,” is highly educated, hardworking and respected, a senior official in Hawaii’s education system. His best friend Mike’s father, the “rich dad,” left school early but went on to build businesses and own property across the islands. Both men love Robert. Both give him advice. The advice almost never agrees.</p><p>Poor dad’s advice is the advice most of us received. Study hard, get good grades, find a safe job with a good employer, and the employer will take care of you. Buy a house, because it is your biggest investment. Be careful with money, avoid risk, and do not talk about money at the dinner table. Rich dad turns each of these upside down. Study hard so you can find a good company to buy, not just to join. Your house is not your best investment. Do not say “I can’t afford it”; ask “how can I afford it?” Learn how money works, because school will not teach you.</p><p>It helps to think of the two dads as two operating systems rather than two people. Poor dad’s system runs on credentials, employment and security. Its main goal is to avoid loss. Rich dad’s system runs on ownership, cash flow and opportunity. Its main goal is to build things that produce income. Neither system is about intelligence. Poor dad is, if anything, the more educated man. The difference is in the questions each one has learned to ask.</p><p>Kiyosaki is not subtle about which system he prefers, and he is unfair to poor dad at times. A stable career, a pension and a professional education are not foolish choices. Many people build very comfortable lives on exactly those foundations. But the contrast earns its place in the book because it makes something visible that is usually invisible: the money beliefs we absorb at home. Most adults never consciously chose their attitude to risk, debt or ownership. They inherited it, the way they inherited an accent.</p><p>Critics have long questioned whether rich dad existed in the form described, and Kiyosaki has always insisted he did. For a reader, that debate matters less than you might think. Rich dad works best as a parable, a character who voices a way of thinking. Read the book that way and it becomes more useful, not less, because you stop asking “did this happen?” and start asking “which of these two voices do I hear when I make decisions?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a8Bw5VtBKOYnJJbDBADaOg.png" /></figure><blockquote><em>The point of the two dads is not that one is clever and one is foolish. It is that money habits are learned, and what was learned can be examined.</em></blockquote><h3>The Rat Race</h3><p>The most famous image Kiyosaki gives us is the rat race. You get a job and a salary. The salary allows a certain lifestyle: an apartment, a car, holidays, the ordinary comforts of adult life. That lifestyle becomes a set of fixed monthly costs. Some of those costs are financed with debt: a car loan, a mortgage, a credit card balance that never quite reaches zero. To keep up, you need your salary to keep arriving. When it rises, the lifestyle rises with it. And so the wheel turns again.</p><p>In the book’s version, rich dad explains this to two young boys after making them work for almost nothing in one of his shops. He wants them to feel the pull of the paycheque, and the frustration of being paid little for their time. The lesson he draws is that most people are driven by two emotions. Fear makes them take a job they do not love because they need the security. Desire makes them spend the raise before it arrives. Between fear and desire, there is little room left for thought.</p><p>What makes the rat race powerful as an idea is that it describes people who are not poor. A doctor, a lawyer or a senior manager can be deep inside it. Their income is high, but so is their rent, their car payment, their school fees and their expectations. If the income stopped for six months, the whole structure would be in trouble. In Kiyosaki’s language, they are still working for money, because almost everything they have depends on the next payment from an employer or a client.</p><p>The way out, in the book’s logic, is not a bigger salary. It is a second engine: income that does not depend on your hours. Kiyosaki even built a board game, CASHFLOW, around this idea. Players start in an inner circle that literally loops, and they escape only when their passive income exceeds their expenses. It is a blunt metaphor, but a memorable one.</p><p>A fair reading adds one caution. Not every rising expense is a trap. Paying more for a safer neighbourhood, a better school or a shorter commute can be a rational trade. The problem Kiyosaki identifies is not spending as such. It is spending that becomes automatic, committed in advance, and financed by a future that has not happened yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MoL-jj81Hj5otYdSBC7x-A.png" /></figure><blockquote><em>The rat race is not about being poor. It is about having no part of your financial life that keeps working when you stop.</em></blockquote><h3>Income Is Not Wealth</h3><p>One of the book’s sharpest points is that income and wealth are different things. Income is a flow. Wealth is what accumulates when part of that flow is kept and put to work. A high earner who spends everything is, financially speaking, in the same position as a low earner who spends everything. Both are one lost job away from trouble. The high earner just has more expensive trouble.</p><p>The mechanism that keeps high earners stuck has a name today: lifestyle inflation. Each pay rise brings a slightly bigger apartment, a newer car, a few more subscriptions. None of these choices looks dramatic on its own. Together they lift the household’s fixed costs until they absorb the rise entirely. Psychologists call the underlying effect the hedonic treadmill: we adapt quickly to new comforts, so the extra spending stops feeling like a treat and starts feeling like a baseline.</p><p>Fixed costs matter more than people think, because they are the part of spending you cannot easily cut. A restaurant habit can end next week. A three-year car lease cannot. A household that commits most of its income to fixed costs has very little room to save, and almost none to absorb a shock. That is why two families with the same salary can have completely different levels of financial security.</p><p>To make this concrete, imagine a household that takes home €4,000 a month after tax. Rent or mortgage takes €1,400. Food takes €500, transport €400, debt repayments and subscriptions another €400, and general lifestyle spending €500. That leaves €800, or 20% of income, for building assets: an emergency fund, investments, perhaps a small business project. These numbers are illustrative, not a recommended budget, but they make one point clear. The single most important number in the picture is not the €4,000. It is the €800.</p><p>Kiyosaki’s own phrase for this is that it is not how much money you make, but how much you keep, and how hard it works for you. The savings rate, the share of income turned into assets, is the bridge between income and wealth. Raise it, and even an ordinary salary starts to build something. Let it fall to zero, and no salary is big enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XQEZHjJ__vcwtv05P80Cw.png" /></figure><blockquote><em>Earning is how money enters your life. Keeping and deploying it is how wealth is built. The book’s lasting contribution is to make that difference feel obvious.</em></blockquote><h3>Assets vs Liabilities</h3><p>If you remember one idea from Rich Dad Poor Dad, it is probably this one. Kiyosaki defines an asset as something that puts money in your pocket, and a liability as something that takes money out of your pocket. That is the whole definition. It is deliberately simple, and it is meant to be applied to everything you own.</p><p>Under this lens, a rental apartment with a tenant who pays more than the mortgage, taxes and maintenance is an asset. A portfolio of shares that pays dividends is an asset. A small business that earns a profit without needing you there every day is an asset. So is intellectual property: a book that earns royalties, a piece of software that sells licences, a course that keeps finding students. In every case, money flows toward you.</p><p>On the other side are things that create recurring outflows: a car financed over five years, a credit card balance at a high interest rate, a large home with heavy running costs, the latest phone on an instalment plan. Kiyosaki’s sharpest observation is that many people buy liabilities while believing they are buying assets. They tell themselves the car is an investment, or that the bigger house will pay off one day, while the monthly cash keeps leaving.</p><p>It is important to be clear about what this definition is and is not. It is not the accounting definition. In standard accounting, an asset is a resource you control that is expected to bring future economic benefit, and a liability is an obligation you owe. Under that definition, your home is an asset on your personal balance sheet, and the mortgage is the liability. Accountants are not wrong. They are answering a different question: what do you own, and what is it worth? Kiyosaki is answering another one: which way does the cash flow each month?</p><p>Both questions matter. The accounting view tells you your net worth. The cash-flow view tells you how long you could survive without a salary. Kiyosaki’s lens is most useful as a test you run on purchases before you make them: will this thing feed me or will I have to feed it? A car you need for work may be a sensible purchase even if it fails the test. The point is to know which column you are adding to, rather than pretending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yb8vUILI5krbH1W4AaISjA.png" /><figcaption>Figure 4 — Kiyosaki’s cash-flow lens: productive ownership sends money toward you, while loans, cards and upgrades create recurring outflows. This is a cash-flow view, not the accounting definition.</figcaption></figure><blockquote><em>Kiyosaki’s definition is a cash-flow lens, not an accounting standard. Used as a lens, it is one of the most useful questions in personal finance.</em></blockquote><h3>The Cash-Flow Quadrant</h3><p>The framework most associated with Kiyosaki actually comes from his follow-up book, Rich Dad’s Cashflow Quadrant, but it grows directly out of the ideas in Rich Dad Poor Dad, and it is now inseparable from them. Kiyosaki divides the ways people earn money into four groups. E is for employee: you work for a salary in someone else’s system. S is for self-employed: you own your job, as a freelancer, a consultant, a small practice. B is for business owner: you own a system that works without you. I is for investor: your money works for you.</p><p>The important line runs down the middle. On the left, E and S, people trade their time for money. If they stop working, the income stops. On the right, B and I, people own systems or capital that keep producing whether or not they show up on a given day. That is the difference between working in a system and owning one. A surgeon in private practice may earn far more than a small shop owner, but the surgeon’s income still depends on the surgeon’s hands.</p><p>Kiyosaki argues that moving toward the right side increases leverage. A business owner can benefit from the work of hundreds of people. An investor can benefit from the work of thousands of companies. Their income is no longer capped by the number of hours in a day. This is a real insight, and it explains why the very wealthy almost always hold most of their wealth as ownership, not as accumulated salary.</p><p>But the quadrant needs careful reading. Employees can and do become wealthy, usually by combining a good salary with a high savings rate and long-term investing. That is, in effect, an E who becomes an I over time. Entrepreneurship is risky: most new businesses fail, and the B quadrant is full of people who lost savings trying to get there. Investing requires capital and knowledge before it produces anything. The quadrant is a map of different income sources, not a ranking of human worth or a law of wealth.</p><p>In practice, most financially secure people live in more than one quadrant at once. A salaried engineer with an investment portfolio and a small side product touches E, I and a little B. That mixture, rather than a heroic leap from one box to another, is how the quadrant actually plays out for most people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSR9SP00tCdGslW1lRjE-Q.png" /></figure><blockquote><em>The quadrant’s best question is not “which box am I in?” but “what share of my income would continue if I stopped working tomorrow?”</em></blockquote><h3>Mind Your Own Business</h3><p>Rich dad’s third lesson sounds like an insult but is actually advice. “Mind your own business” in the book means: pay attention to your own asset column, not just your job. Kiyosaki argues that most people confuse their profession with their business. Their profession is what they do for a living. Their business, in his sense, is the collection of assets they personally own and grow.</p><p>This is why he tells readers to keep their day job while building something on the side. The job pays the bills. The asset column is what eventually buys freedom. A banker may spend forty years managing other people’s money and own very little herself. An engineer may build systems that earn millions for a company and never build one that earns anything for himself. The professional work is valuable. It is just not, by itself, a business of your own.</p><p>Take a software engineer in 2026. Her profession gives her a salary. Her own business might include an emergency fund, a monthly investment into a global index fund, employee stock awarded by her company, a small software tool that earns a few hundred euros a month, and some technical writing or courses that create intellectual property. None of these needs to be dramatic. Together they form a second balance sheet that belongs to her, not to her employer.</p><p>Kiyosaki adds a rule about luxuries that is worth remembering: buy them last, and ideally buy them with income from assets rather than with salary or debt. If your portfolio pays for the holiday, the holiday costs you nothing in future freedom. If a loan pays for it, you are trading future freedom for present pleasure. This is stricter than most people want to live, but the principle is sound.</p><p>The main nuance is that “minding your own business” should not come at the expense of doing your job well. Your career is often your most valuable asset in your twenties and thirties, because it funds everything else. The idea is not to neglect the profession. It is to stop assuming the profession is the whole plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tW1GMsfrcQfweka8n7AuBA.png" /></figure><blockquote><em>Your job is how you earn. Your asset column is what you keep. The book asks you to build the second without neglecting the first.</em></blockquote><h3>Why Financial Literacy Matters</h3><p>Kiyosaki’s frustration with the school system runs through the whole book. Students learn algebra, history and literature, but most leave school unable to read a payslip, compare two loans or understand what their pension fund is doing. He argues that this is why intelligent, well-educated people so often struggle with money: they were never taught the language.</p><p>The language he means is accounting, at a very basic level. An income statement shows money coming in and going out over a period: salary, rent, food, interest. A balance sheet shows what you own and what you owe at a point in time: savings, investments, property, loans. Cash flow is the difference between what comes in and what goes out. Net worth is assets minus liabilities. None of this is advanced. Most people simply never draw it for their own life.</p><p>What changes when you do? Decisions start to look different. A €30,000 car on a five-year loan is no longer “€450 a month, which I can handle.” It is a liability on the balance sheet, an outflow on the income statement, and a drag on cash flow for five years. A €200 monthly investment is no longer “money I can’t spend.” It is a growing line on the asset side. Seeing your finances as statements turns vague feelings into trade-offs you can actually weigh.</p><p>Kiyosaki’s specific claim is that the rich and the middle class have differently shaped statements. The rich, he says, have income flowing in from the asset column. The middle class has income flowing in from a job and out to liabilities they mistake for assets. Whether or not that is true of every family, it is a very useful diagnostic. You can sketch your own statements in an hour and see which shape you have.</p><p>The book’s limit here is that it stops at the basics. It does not teach investing, diversification or risk measurement in any depth. A modern reader should treat Rich Dad Poor Dad as the reason to become financially literate, not as the education itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FX9BJ6yN-Wk-ByhxXWV0RA.png" /></figure><blockquote><em>You cannot manage what you never write down. Two simple statements, kept honestly, change more decisions than any single investment tip.</em></blockquote><h3>Work to Learn, Not Only to Earn</h3><p>One of the book’s most practical chapters tells young people to choose jobs for what they will learn, not only for what they will earn. Kiyosaki describes his own path in this light. After military service he took a sales job at Xerox, not because he loved photocopiers, but because he was terrified of rejection and knew sales would force him to face it. He stayed until he was among the company’s top salespeople, then left to start his own ventures.</p><p>His argument is that schools and careers reward specialisation, but wealth often rewards combination. A brilliant specialist who cannot sell, negotiate, manage people or read a balance sheet may stay dependent on an employer forever. Someone who knows “a little about a lot” can see how a whole business works and is more likely to build one. He uses a well-known example: many people can cook a better burger than a global fast-food chain, but very few can build a better business system around a burger.</p><p>The skills he values most are communication skills: sales, writing, speaking and negotiation. He calls the ability to sell the foundation of personal success, and in a narrow sense he is right. Almost every path to ownership, from raising money to hiring to finding customers, depends on persuading other people.</p><p>In 2026 the list needs updating, but the logic holds. Data literacy, product thinking and the ability to use AI tools well now sit alongside sales and writing as skills that transfer across industries. A developer who learns product management, a marketer who learns to build with AI, an analyst who learns to present and negotiate: each is widening the set of things they could do, not just deepening one job. That widening is the real return. It shows up as more choices before it shows up as more money.</p><p>There is a fair objection. Not everyone can afford to take a lower-paid job for the learning, especially with rent or family to pay for. The principle still applies inside most jobs: volunteer for the project that teaches something new, take the role closer to customers, learn the part of the business you do not understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGh0a6zOMqFjDWrVv_Ty8w.png" /></figure><blockquote><em>The best career investments are skills that travel. They raise income, but more importantly they multiply options.</em></blockquote><h3>Build the Asset Column</h3><p>Underneath all of Kiyosaki’s lessons sits a simple loop. You earn. You keep part of what you earn. You use what you keep to acquire something productive. That thing produces income or value. You reinvest that income into more productive things. Then you repeat, for years. The book’s examples tend to involve property and small businesses, but the loop works with almost any productive asset.</p><p>The first two steps are where most people get stuck, which is why Kiyosaki spends so much time on “pay yourself first.” His version is extreme: he describes paying himself first even when it meant paying bills late, using the pressure of the bills to force himself to find more income. Most readers should not copy that. Late payments carry real costs, from fees to damaged credit. But the core idea is right: savings that wait for whatever is left at the end of the month rarely happen. Automating a transfer on payday turns good intentions into a habit.</p><p>The third step, acquiring productive assets, is where knowledge matters. A productive asset can be a share of a company through a fund, a property with genuine positive cash flow, a business, or something you create. Each has different risks, costs and demands on your time. The book’s enthusiasm for property, for example, glosses over vacancies, maintenance, financing risk and the time a landlord spends. The goal is not to collect any asset, but to understand what you buy.</p><p>The fourth and fifth steps are where patience pays. The income from assets is usually small at first. Reinvested, it buys more assets, which produce more income. Over time the loop accelerates. This is why Kiyosaki insists that the rich “buy luxuries last”: spending asset income too early breaks the loop exactly when it is starting to work.</p><p>A tree is a good picture for this. Its roots are the things that come before money: skills, a stable income, discipline. Its trunk is capital, the accumulated savings that everything else grows from. Its branches are different kinds of assets. And its fruit, eventually, is cash flow, freedom and options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMcsGHzqM3FGQ0-DO48tmA.png" /></figure><blockquote><em>Wealth is less a decision than a loop: earn, keep, own, reinvest, repeat. The loop is slow at first and then surprisingly fast.</em></blockquote><h3>The Power of Compounding</h3><p>Kiyosaki writes about compounding mostly through stories, but it is the hidden engine behind almost everything he recommends, so it is worth explaining properly. Compounding means earning returns on your past returns. If an investment grows by 8% in a year, next year’s 8% is calculated on the larger amount. The growth begins to grow.</p><p>Consider an illustration. Someone invests €500 a month for 30 years and earns a hypothetical 8% a year, compounded monthly, with all returns reinvested. After 5 years the account holds about €36,700. After 10 years, about €91,500. After 20 years, about €294,500. After 30 years, about €745,200. Over the full period the investor contributed €180,000. The other €565,000 or so is growth.</p><p>Look at how that growth is distributed. In the first ten years, growth adds only about €31,000 on top of €60,000 of contributions. In the last ten years alone, the account rises by roughly €450,000. More than half of the final value arrives in the final decade. That is what compounding feels like from the inside: very slow, then suddenly fast. It also explains why starting early matters more than starting big. The early euros have the most time to grow.</p><p>Three forces drive the result. Time, because compounding needs many periods to work. Contributions, because regular additions give the engine more fuel. And returns, because the rate determines how quickly growth builds on itself. Reinvestment is what connects them. Spend the returns and you have simple interest; reinvest them and you have compounding.</p><p>This is an illustration, not a forecast. Real investments do not return a steady 8% each year. Markets fall, sometimes for years. Fees, taxes and inflation all reduce what you keep, and 8% in nominal terms is not 8% in purchasing power. A careful reader should treat the numbers as a way to understand the shape of compounding, not as a promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ucfHHZ89vACgmEWhZxKABA.png" /></figure><blockquote><em>Compounding rewards two things most people find hard: starting before it feels necessary, and leaving the money alone.</em></blockquote><h3>Why the Rich “Invent Money”</h3><p>The fifth lesson in the book has the most provocative title: the rich invent money. Read literally, it sounds like a promise of something from nothing. It is not. What Kiyosaki means is that financially skilled people create opportunities rather than waiting for them, by combining knowledge, relationships and capital in ways others do not see.</p><p>His examples come mostly from property deals. He describes buying homes cheaply during a downturn, often in foreclosure, and reselling them quickly at a profit, sometimes without much of his own money. The deals worked because he understood the local market, could arrange financing, and was willing to act while others were afraid. The “money” was invented in the sense that it came from a recognised opportunity, not from a salary.</p><p>The broader interpretation is more useful. Value is created when someone solves a problem: a buyer who needs a house, a company that needs software, a market that lacks a product. People who notice problems and know how to connect knowledge, people and tools to solve them tend to find opportunities everywhere. People who only look for job adverts see far fewer. In that sense, opportunity is partly a skill you can train.</p><p>Leverage plays a role too. Kiyosaki talks about using other people’s money, through loans and partners, to do more than your own capital would allow. Leverage can magnify gains. It also magnifies losses, which is exactly why many of the property investors who used it most aggressively were hurt badly in 2008. Leverage belongs in the toolbox, but it is the sharpest tool in it.</p><p>He also makes a point about education: invest in your financial knowledge first, because a trained mind sees deals an untrained mind misses. That is fair, with one warning. Some of the people who sell “financial education” mostly sell it to themselves. Learn from many sources, check claims, and be wary of anyone whose main product is the promise of easy deals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPDM1KCNLbj-cnqhxvdtng.png" /></figure><blockquote><em>Nobody invents money from nothing. What some people learn to do is see problems as opportunities and connect the skills and capital needed to solve them.</em></blockquote><h3>Fear, Failure and Risk</h3><p>Kiyosaki believes that the main thing separating people who build wealth from those who do not is not intelligence but how they handle fear. He lists the obstacles that stop even financially literate people: fear of losing money, cynicism, laziness, bad habits and arrogance. Of these, fear gets the most attention. Most people, he argues, play not to lose rather than playing to win.</p><p>He describes losing money himself and treating it as tuition. Failure, in his view, is how people learn, just as children learn to walk by falling. Rich dad, at one point, explains the difference between being broke and being poor: “Broke is temporary, poor is eternal.” The idea is that a financial setback is an event, while a mindset of scarcity is a condition.</p><p>There is real wisdom here. People who never take any risk at all often end up with very little, because cash in a savings account slowly loses value to inflation and because the biggest opportunities usually require some uncertainty. Learning to tolerate a portfolio that moves up and down, or a project that might fail, is a genuine financial skill.</p><p>But the book also blurs a line that matters enormously: the line between calculated risk and recklessness. A calculated risk is one where you understand what could go wrong, the downside is limited to something you can survive, and the potential reward justifies it. A reckless risk is one where the downside is unknown, or could wipe you out, or is financed with money you cannot afford to lose.</p><p>Several practical tools separate the two. Keep an emergency buffer, so a setback does not force you to sell at the worst time. Size positions so that no single bet can ruin you. Diversify, because concentration is how ordinary investors lose everything. Understand liquidity: some assets cannot be sold quickly. Learn before you invest, not after. Kiyosaki sometimes praises concentration and boldness in ways that work beautifully in hindsight for the people who survived. The people who did not survive rarely write best-sellers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mua9aMEf887_NFXiXUl1ug.png" /></figure><blockquote><em>Risk is not the enemy of wealth. Ruin is. The skill is taking risks you can survive.</em></blockquote><h3>Taxes, Corporations and Financial Systems</h3><p>In one of the book’s most American chapters, rich dad tells a short history of taxes. Income tax, he says, was sold to the public as a tax on the rich, but over time it fell mostly on the middle class. The rich, meanwhile, protected themselves using legal structures, especially corporations, and expert advice. The key, in his telling, is the order of operations. An employee earns, is taxed, then spends what is left. A business owner with a corporation earns, spends on legitimate business costs, and is taxed on what remains.</p><p>There is a real principle buried in this. Tax systems do treat income differently depending on how it is earned and held. Business expenses are usually deductible. Capital gains, dividends and salaries are often taxed at different rates. Holding structures, pensions and retirement accounts can change when and how tax is paid. Understanding these rules is a legitimate part of financial literacy, and a good adviser can save far more than they cost.</p><p>But this is the section where a European reader must be most careful. Kiyosaki’s examples come from the United States, with its specific corporate forms and tax code. Luxembourg, France, Germany, the United Kingdom and the US each have different rules on company taxation, deductible expenses, dividend taxation, social contributions and substance requirements. A structure that is efficient in one country may be useless or even illegal in another.</p><p>In most European systems, running personal expenses through a company is treated as a hidden distribution of profit or a taxable benefit, with penalties attached. EU anti-avoidance rules have also tightened over the past decade. Cross-border situations, which are common in a place like Luxembourg, add another layer: where you live, where you work and where your company is registered can each matter.</p><p>The safe lesson is general: learn how your own tax system treats different kinds of income, and get qualified advice before setting up structures. The unsafe lesson is specific: copying an American strategy from a 1997 book. Nothing in this section, or in the book, is tax advice for your situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Em6r1gYChkFLCfFla2bLzg.png" /><figcaption>Figure 13 — Same idea, different roads: tax and corporate rules change at every border. Strategies written for the US do not travel automatically to the UK, France, Luxembourg or Germany.</figcaption></figure><blockquote><em>The principle travels: understand how income is taxed. The tactics do not: always check local rules and take qualified advice.</em></blockquote><h3>Financial Freedom</h3><p>Kiyosaki’s definition of financial freedom is precise and useful. You are financially free when the income from your assets covers your expenses. At that point a job becomes a choice rather than a necessity. You may still work, and many people do, but you no longer have to.</p><p>Take a simple illustration. Suppose your essential expenses are €2,500 a month. If your assets generate €1,000 a month, you are not free, but you have a real cushion: you could survive a cut in hours or a period between jobs far more easily. At €1,800 you are getting close; a part-time job or a modest freelance income would close the gap. At €2,500 you reach a conceptual break-even, where asset income covers essential costs. At €3,200 you have a margin above expenses, which you will need, as we will see.</p><p>The threshold matters because it changes your relationship with work. Below it, every career decision carries the weight of survival. Above it, you can choose a lower-paid job you care about, take time to care for family, or start a business without betting the household. Even getting part of the way there changes how fear and opportunity feel.</p><p>The simple version, however, leaves out several things. Inflation raises expenses over time: €2,500 a month today becomes roughly €3,700 in twenty years at 2% annual inflation. Taxes reduce asset income. Investment income is not steady; dividends can be cut and tenants can leave. Expenses change with life events, children, health and housing. And unexpected costs arrive whether or not you planned for them.</p><p>That is why a careful definition of financial freedom includes a margin. Break-even is a milestone, not a finish line. The €3,200 in the illustration is not greed; it is the buffer that keeps freedom from collapsing at the first bad year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UJuojrRPKh8Ze3LWo-zPpQ.png" /></figure><blockquote><em>Financial freedom is not a number in your account. It is the point where your assets, not your employer, pay for your essential life, with room to spare.</em></blockquote><h3>What Rich Dad Poor Dad Gets Right</h3><p>It is easy to criticise this book, and we will. But its success is not an accident. It gets several important things right, and it explains them in a way that ordinary people remember.</p><p>First, it puts financial literacy at the centre. The idea that you should understand your own income statement and balance sheet, and that schools rarely teach this, is as true now as in 1997. Second, it teaches cash-flow awareness. Asking whether something brings money in or takes money out is a simple habit that prevents a large number of bad decisions.</p><p>Third, it names lifestyle inflation and the rat race clearly enough that readers recognise themselves. Fourth, it shifts attention from wages toward ownership: of businesses, of investments, of creative work. Fifth, it values transferable skills, especially communication and sales, over narrow credentials. Sixth, it encourages long-term thinking, the patience to build an asset column before spending its output.</p><p>Seventh, it favours multiple sources of income over total dependence on one employer, an idea that has aged well in an era of layoffs and automation. And eighth, perhaps most importantly, it treats money as psychological. Fear, desire, cynicism and habit shape financial lives more than spreadsheets do. Many later and more rigorous books, on behavioural finance and the psychology of money, make the same point with better evidence.</p><p>None of these ideas is original to Kiyosaki. What he did was package them into a story that people actually finish reading. For many readers, it is the first book that made money feel like something they could understand and control. That is not a small achievement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hsqUh0P6ruBiT2NWWnY42g.png" /></figure><blockquote><em>The book’s lasting value is not a strategy. It is a set of questions that stay useful whatever your income or country.</em></blockquote><h3>What Rich Dad Poor Dad Gets Wrong or Oversimplifies</h3><p>The book’s biggest weakness is that it presents a useful lens as if it were the whole truth. Several of its famous claims need context before anyone acts on them.</p><p>Start with the house. Kiyosaki’s claim that your home is a liability is true under his cash-flow definition: a home you live in does not pay you rent, and it costs money every month. But a paid-off home removes your largest expense, which is economically similar to receiving rent. Over long periods, home ownership has been a major source of household wealth in many countries. The accurate statement is narrower: a home is a consumption choice and a concentrated, illiquid investment, and a bigger home is not automatically a better one.</p><p>Next, “the rich don’t work for money.” Most wealthy people work very hard, and many high earners became wealthy precisely by investing a large salary over decades. The useful interpretation is about dependence: wealth grows when your financial life does not rest entirely on your own labour. Taken literally, the phrase is wrong.</p><p>The book also romanticises entrepreneurship. It treats starting businesses as the obvious path and rarely discusses the high failure rate, the personal cost, or the role of luck and timing. Its treatment of taxes and corporations is simplified even for the US, and potentially misleading elsewhere. Its attitude to risk sometimes reads as encouragement to be bold without the risk management that makes boldness survivable. And it has a strong bias toward real estate, partly reflecting the author’s own experience, with little attention to the low-cost diversified investing that has served ordinary savers well.</p><p>There are deeper methodological problems. The book is almost entirely anecdotal; there is very little evidence behind its claims. It suffers from survivorship bias, telling the story of the deals that worked. And it sometimes blurs net worth and cash flow, two measures that answer different questions. A property with positive cash flow can still destroy net worth if its value falls, and a portfolio with little cash flow can build large net worth through growth.</p><p>None of this makes the book worthless. It makes it a framework that needs a second source. Read it for the questions it asks, then check the answers somewhere more rigorous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpIchBjMs2GaGpIWrPIRQg.png" /><figcaption>Figure 16 — Weighing the book: a useful framework on one side; on the other, ideas that need context, such as the house, the tax tactics and the attitude to risk.</figcaption></figure><blockquote><em>Rich Dad Poor Dad is a good first book about money and a poor last one. Its lens is valuable; its specific advice needs checking.</em></blockquote><h3>What the Book Means in 2026</h3><p>When Kiyosaki wrote the book, the obvious asset for an ordinary person was a rental property, and the obvious business was a physical one. Building either took serious capital. In 2026 the menu of productive assets is far wider, and many items on it are within reach of someone with a normal salary.</p><p>The most accessible is broad index investing. Low-cost exchange-traded funds let anyone own small slices of thousands of companies, with monthly contributions as small as a few tens of euros at many brokers. In Kiyosaki’s terms, this is the I quadrant made available to everyone. It is not glamorous, and it does not feature heavily in the book, but for most savers it is the simplest way to make money work without becoming a landlord or a founder.</p><p>Then there are digital assets in the old-fashioned sense of the word: things you build that keep earning. Software and small SaaS products can sell while their creator sleeps. Courses, books, newsletters, templates and design assets are forms of intellectual property that the creator economy has made easier to sell. AI tools have lowered the cost of building many of these things, which means a single person can now produce what once needed a small team.</p><p>Work itself has changed. Remote and cross-border work has widened the job market for many professionals, and equity compensation, stock options and share awards, has turned some employees into part-owners. Global investing lets a saver in Luxembourg own companies in Asia and America with a few clicks. At the same time, automation and AI are changing which forms of labour remain well paid, which makes Kiyosaki’s warning about depending entirely on one income stream more relevant, not less.</p><p>So the modern version of “build your asset column” has many routes. A developer can build software. A creator can build intellectual property. A professional can build an investment portfolio alongside a career. An entrepreneur can build equity in a company. An employee can accumulate shares in the business they work for. The common thread is ownership of something that keeps producing value. The particular form matters much less than it did in 1997.</p><p>One caution belongs here too. Some of today’s “passive income” ideas are neither passive nor income. Many online courses, trading schemes and get-rich systems sell the dream of the B and I quadrants without the substance. Kiyosaki’s own lens is the best defence: does this thing put money in your pocket, or take it out?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iS0kJcJi9CpAfRfIXg6GEA.png" /><figcaption>Figure 17 — The 2026 skyline of assets: career, index funds, software, business, intellectual property and equity are all routes to ownership. A rental property is now just one of them.</figcaption></figure><blockquote><em>In 2026 an asset does not have to be a building. It can be a fund, a product, a body of work or a slice of a company.</em></blockquote><h3>The Book in One Mental Model</h3><p>Strip away the anecdotes, the exaggerations and the American tax tricks, and Rich Dad Poor Dad leaves behind a single loop that is worth keeping. It starts with learning: understanding how money works, reading your own numbers, building skills that others value. Learning leads to earning, usually first through a job.</p><p>Earning leads to the first real decision: controlling cash flow. That means keeping fixed costs below income, resisting lifestyle inflation, and paying yourself first. Controlled cash flow creates savings, and savings become the capital to build assets: funds, businesses, property, intellectual property, equity.</p><p>Assets generate value and, eventually, cash flow. The disciplined move is to reinvest that cash flow rather than spend it immediately, so the loop accelerates. Along the way you keep building skills, because better skills raise income and widen the range of assets you can understand and own.</p><p>The output of the loop is not simply more money. It is more options: the ability to change jobs, take a risk, rest, help family, or start something new without fear of collapse. That is the quietly radical idea at the centre of the book. Wealth is not a number. It is a range of choices.</p><p>The loop is not a straight line, either. It climbs, then circles back, then climbs again. You learn, earn and invest, and then you find yourself learning again, at a higher level, with more at stake and more to work with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gvaAD-zuPZH3LwT2mFNRQ.png" /><figcaption>Figure 18 — The whole book as one rising loop: learn, earn, control cash flow, build assets, generate value, reinvest, build skills, and arrive at more options before the next turn.</figcaption></figure><blockquote><em>Learn, earn, keep, own, reinvest, grow. Repeat until the job is a choice.</em></blockquote><h3>The Better Question</h3><p>Rich Dad Poor Dad is often sold as a book about how to get rich. That is probably why it has disappointed so many readers who looked inside for a method. There is no method. There is a way of seeing.</p><p>Read today, its best lessons survive almost intact. Income is not wealth. Cash flow tells the truth. Ownership compounds while wages do not. Skills that travel are worth more than titles that do not. Fear and habit decide more than intelligence. Its weakest lessons need to be left in 1997: the casual attitude to risk, the tax tactics of another country, the idea that a home is simply a mistake.</p><p>The question the book leaves behind is not “How do I become rich?” That question has too many answers, most of them sold by someone. A better question is quieter and more honest: am I building a financial life that gives me more choices five years from now than I have today?</p><p>If the answer is yes, you are already doing the important part of what Kiyosaki was trying to teach. If the answer is no, the book, for all its flaws, is a good place to start asking why.</p><h3>References and notes</h3><p><strong>Primary source.</strong> Robert T. Kiyosaki with Sharon L. Lechter, Rich Dad Poor Dad: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not! (first published 1997; 20th anniversary edition, Plata Publishing, 2017).</p><p><strong>Disclaimer.</strong> This essay is for education and discussion only. It is not investment, tax or legal advice. Tax and corporate rules differ by country and change over time; consult a qualified adviser about your own situation. All illustrations are original works created for this essay.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=168d9db48ff5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embracing Modern SQLAlchemy 2.0: DeclarativeBase, Mapped[], and Beyond]]></title>
            <link>https://medium.com/@azizmarzouki/embracing-modern-sqlalchemy-2-0-declarativebase-mapped-and-beyond-ef8bcba1e79c?source=rss-233f593038ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef8bcba1e79c</guid>
            <category><![CDATA[declartivebase]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[mapped]]></category>
            <dc:creator><![CDATA[Aziz Marzouki]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 10:27:56 GMT</pubDate>
            <atom:updated>2025-03-27T10:27:56.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CTXRZ9RZSTo3zXKM.jpg" /></figure><p>SQLAlchemy 2.0 has ushered in a wave of modernization that aligns the powerful ORM with Python’s latest features, such as static typing, better IDE support, and cleaner code. If you’re still using SQLAlchemy 1.x style syntax, it’s time to take a look at what SQLAlchemy 2.0 brings to the table. In this article, we’ll explore the most important modern features: DeclarativeBase, Mapped[], mapped_column(), and several others that enhance both clarity and productivity.</p><h3>1. DeclarativeBase: A Cleaner Foundation for Your Models</h3><h3>Old Way:</h3><pre>from sqlalchemy.ext.declarative import declarative_base<br>Base = declarative_base()</pre><h3>New Way:</h3><pre>from sqlalchemy.orm import DeclarativeBase<br>class Base(DeclarativeBase):<br>    pass</pre><h3>Why It’s Better:</h3><ul><li><strong>Clear Inheritance</strong>: You now explicitly define your own base class.</li><li><strong>Extensibility</strong>: Inject shared behaviors or metadata across all models.</li><li><strong>Type-Safe</strong>: Better compatibility with type checkers and IDEs.</li></ul><h3>2. Mapped[]: Native Typing for ORM Fields</h3><h3>Old Way:</h3><pre>id = Column(Integer, primary_key=True)</pre><h3>New Way:</h3><pre>from sqlalchemy.orm import Mapped, mapped_column<br>id: Mapped[int] = mapped_column(primary_key=True)</pre><h3>Why It’s Better:</h3><ul><li><strong>Static Typing</strong>: Improves readability and helps catch bugs early.</li><li><strong>IDE Integration</strong>: Enhances autocompletion and documentation.</li><li><strong>Pythonic</strong>: Aligns with type hinting introduced in modern Python.</li></ul><h3>3. mapped_column(): Replacing Column</h3><h3>Old Way:</h3><pre>from sqlalchemy import Column, Integer<br>id = Column(Integer, primary_key=True)</pre><h3>New Way:</h3><pre>id: Mapped[int] = mapped_column(Integer, primary_key=True)</pre><h3>Why It’s Better:</h3><ul><li><strong>Consistency</strong>: Cleaner integration with Mapped[].</li><li><strong>Declarative</strong>: More readable and type-friendly.</li></ul><h3>4. select() as the Primary Query Interface</h3><h3>Old Way:</h3><pre>session.query(User).filter_by(name=&quot;Alice&quot;)</pre><h3>New Way:</h3><pre>from sqlalchemy import select<br><br>stmt = select(User).where(User.name == &quot;Alice&quot;)<br>result = session.execute(stmt).scalars().all()</pre><h3>Why It’s Better:</h3><ul><li><strong>Explicit and Composable</strong>: Easier to construct and chain queries.</li><li><strong>Unified API</strong>: Same approach across Core and ORM.</li></ul><h3>5. Async ORM Support</h3><p>SQLAlchemy 2.0 includes native async support using async / await, enabling you to build fully asynchronous apps with the ORM.</p><pre>from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine<br><br>engine = create_async_engine(&quot;postgresql+asyncpg://user:pass@host/db&quot;)<br>session = AsyncSession(engine)</pre><h3>Why It’s Better:</h3><ul><li><strong>Non-blocking I/O</strong>: Ideal for FastAPI and modern async web frameworks.</li><li><strong>First-Class Support</strong>: Built directly into the ORM now.</li></ul><h3>6. registry() for Flexible Mappings</h3><p>While DeclarativeBase is most common, SQLAlchemy 2.0 also supports flexible class mappings using a registry().</p><pre>from sqlalchemy.orm import registry<br><br>mapper_registry = registry()<br>@mapper_registry.mapped<br>class MyClass:<br>    __tablename__ = &quot;myclass&quot;<br>    id: Mapped[int] = mapped_column(primary_key=True)</pre><h3>Why It’s Useful:</h3><ul><li><strong>Decoupled Models</strong>: Enables alternative mapping styles (imperative or hybrid).</li><li><strong>Greater Control</strong>: Useful for advanced configurations.</li></ul><h3>7. Annotated Declarative Table Support</h3><p>You can now fully use Python’s typing.Annotated to include additional metadata, like column constraints, in a more structured way.</p><pre>from typing import Annotated<br>from sqlalchemy import String<br><br>name: Mapped[Annotated[str, mapped_column(String(50))]]</pre><h3>Why It’s Better:</h3><ul><li><strong>Type-First</strong>: More powerful integration with typing tools.</li><li><strong>Future-Proof</strong>: Leverages Python’s evolving typing ecosystem.</li></ul><h3>8. Better Defaults and On-Update Behavior</h3><p>SQLAlchemy 2.0 promotes the use of callables for dynamic defaults and update hooks.</p><pre>from datetime import datetime, timezone<br><br>created_at: Mapped[datetime] = mapped_column(default=lambda: datetime.now(timezone.utc))<br>updated_at: Mapped[datetime] = mapped_column(onupdate=lambda: datetime.now(timezone.utc))</pre><h3>Putting It All Together</h3><p>Here’s a complete modern SQLAlchemy 2.0 model:</p><pre>from datetime import datetime, timezone<br>from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column<br>from sqlalchemy import Integer<br><br>class Base(DeclarativeBase):<br>    pass<br>class User(Base):<br>    __tablename__ = &quot;users&quot;<br>    id: Mapped[int] = mapped_column(Integer, primary_key=True)<br>    name: Mapped[str]<br>    created_at: Mapped[datetime] = mapped_column(default=lambda: datetime.now(timezone.utc))<br>    updated_at: Mapped[datetime] = mapped_column(onupdate=lambda: datetime.now(timezone.utc))</pre><h3>Conclusion</h3><p>SQLAlchemy 2.0 isn’t just an upgrade — it’s a transformation. By embracing features like DeclarativeBase, Mapped[], mapped_column(), async support, and improved typing, you make your ORM layer more readable, maintainable, and aligned with modern Python standards.</p><p>If you’re starting a new project or refactoring an older codebase, now is the perfect time to adopt these practices and unlock the full power of SQLAlchemy 2.0.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef8bcba1e79c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Scalable Microservices with FastAPI: Architecture, Logging, and Config Made Simple]]></title>
            <link>https://medium.com/@azizmarzouki/build-scalable-microservices-with-fastapi-architecture-logging-and-config-made-simple-92e35552a707?source=rss-233f593038ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/92e35552a707</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Aziz Marzouki]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 09:00:04 GMT</pubDate>
            <atom:updated>2025-03-27T09:00:04.799Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*NE_UqCcpvaauoxdX" /></figure><p><em>Modern applications demand more than just working APIs — they need to be scalable, modular, and easy to deploy. This is where </em><strong><em>FastAPI</em></strong><em> shines when combined with </em><strong><em>microservice principles</em></strong><em>.</em></p><p>In this deep-dive article, we’ll walk through building a university ERP system using FastAPI by applying:</p><ul><li>Decomposition patterns</li><li>Microservice mounting</li><li>A simple API gateway workaround</li><li>Centralized logging (with Loguru)</li><li>Inter-service communication (via httpx and requests)</li><li>Domain-driven design</li><li>Externalized configurations (with Pydantic and dotenv)</li></ul><p>Let’s unpack this transformation step-by-step.</p><h3>🧱 1. Decomposition: From Monolith to Microservices</h3><p>Instead of cramming everything into one large FastAPI project, we break the ERP app into <strong>subdomains</strong> or <strong>business units</strong>:</p><ul><li><strong>Student Management</strong></li><li><strong>Faculty Management</strong></li><li><strong>Library Services</strong></li></ul><p>Each unit becomes an independent FastAPI microservice, with its own server, routes, and lifecycle.</p><pre>uvicorn main:student_app --port 8001<br>uvicorn main:faculty_app --port 8002<br>uvicorn main:library_app --port 8003</pre><p>This aligns with the <strong>12-Factor App</strong> principles — separation of concern, independent deployment, and easy scaling.</p><h3>🧩 2. Mounting Microservices</h3><p>FastAPI allows you to <strong>mount apps</strong> into a top-level app. Think of it as grouping services under a common gateway:</p><pre>from fastapi import FastAPI<br>from student_mgt import student_main<br>from faculty_mgt import faculty_main<br>from library_mgt import library_main</pre><pre>app = FastAPI()</pre><pre>app.mount(&quot;/student&quot;, student_main.student_app)<br>app.mount(&quot;/faculty&quot;, faculty_main.faculty_app)<br>app.mount(&quot;/library&quot;, library_main.library_app)</pre><p>Now all sub-services are accessible via:</p><ul><li>/student/...</li><li>/faculty/...</li><li>/library/...</li></ul><p>And they can still run independently when needed!</p><h3>🌐 3. Creating a Simple API Gateway</h3><p>A real-world system often uses a <strong>reverse proxy</strong> like NGINX, but we can simulate an <strong>API Gateway</strong> with FastAPI.</p><p>We define an endpoint like /university/{portal_id} and redirect based on the ID:</p><pre>@router.get(&quot;/university/{portal_id}&quot;)<br>def access_portal(portal_id: int):<br>    return {&quot;message&quot;: &quot;University ERP Systems&quot;}</pre><p>Then add a custom <strong>dependency</strong> to evaluate the portal_id:</p><pre>def call_api_gateway(request: Request):<br>    portal_id = request.path_params[&quot;portal_id&quot;]<br>    if portal_id == &quot;1&quot;:<br>        raise RedirectStudentPortalException()<br>    elif portal_id == &quot;2&quot;:<br>        raise RedirectFacultyPortalException()<br>    elif portal_id == &quot;3&quot;:<br>        raise RedirectLibraryPortalException()</pre><p>Each of these exceptions is handled with a redirect:</p><pre>@app.exception_handler(RedirectStudentPortalException)<br>def handle_student_redirect(request, exc):<br>    return RedirectResponse(url=&quot;/student/index&quot;)</pre><p>This creates a basic but functional API gateway using just FastAPI core features.</p><h3>📄 4. Centralized Logging with Loguru</h3><p>Traditional logging can fail in async-heavy frameworks. Enter loguru, a developer-friendly, thread-safe logging library.</p><pre>pip install loguru</pre><p>Initialize it in your main app:</p><pre>from loguru import logger</pre><pre>logger.add(&quot;info.log&quot;, format=&quot;{time} - {level} - {message}&quot;, level=&quot;INFO&quot;, enqueue=True)</pre><p>Then wrap requests in a <strong>logging middleware</strong>:</p><pre>@app.middleware(&quot;http&quot;)<br>async def log_middleware(request: Request, call_next):<br>    logger.info(f&quot;Accessing {request.url.path}&quot;)<br>    response = await call_next(request)<br>    logger.info(f&quot;Finished {request.url.path}&quot;)<br>    return response</pre><p>This logs every API hit across all mounted microservices, with support for async logging and custom formatting.</p><h3>🔁 5. Inter-Service Communication with httpx and requests</h3><h3>Using httpx (async)</h3><pre>import httpx<br><br>@router.get(&quot;/assignments&quot;)<br>async def list_assignments():<br>    async with httpx.AsyncClient() as client:<br>        res = await client.get(&quot;http://localhost:8002/faculty/assignments&quot;)<br>        return res.json()</pre><h3>Using requests (sync)</h3><pre>import requests<br><br>@router.post(&quot;/books/request&quot;)<br>def borrow_book(data: BookRequest):<br>    with requests.Session() as sess:<br>        res = sess.post(&quot;http://localhost:8003/library/borrow&quot;, json=data.dict())<br>        return res.content</pre><p>Both methods are useful, depending on whether your endpoints are sync or async. Always convert BaseModel to JSON using jsonable_encoder() or .dict().</p><h3>🧠 6. Domain-Driven Design: Modeling Your Services</h3><p>To keep logic organized, apply <strong>Domain Modeling</strong> using a layered architecture:</p><ul><li>models/ – domain and request models</li><li>repository/ – handles data persistence</li><li>service/ – business logic</li><li>controller/ – FastAPI route logic</li></ul><h3>Example: Faculty Assignment Repository</h3><pre>class AssignmentRepository:<br>    def insert(self, assignment):<br>        faculty_assignments[assignment.id] = assignment<br>    def get_all(self):<br>        return list(faculty_assignments.values())</pre><h3>Example: Faculty Assignment Service</h3><pre>class AssignmentService:<br>    def __init__(self):<br>        self.repo = AssignmentRepository()<br>    def add_assignment(self, assgn: Assignment):<br>        return self.repo.insert(assgn)</pre><p>You can also inject repositories via Depends() to decouple layers further.</p><h3>⚙️ 7. Managing Configs with pydantic.BaseSettings</h3><p>Stop hardcoding configs! Instead, create typed settings:</p><pre>class StudentSettings(BaseSettings):<br>    application: str = &quot;Student Portal&quot;<br>    webmaster: str = &quot;admin@university.edu&quot;</pre><p>Load them with Depends():</p><pre>def get_settings():<br>    return StudentSettings()<br><br>@app.get(&quot;/index&quot;)<br>def index(settings: StudentSettings = Depends(get_settings)):<br>    return {&quot;app&quot;: settings.application}</pre><p>Or load from .env or .properties:</p><pre>class ServerSettings(BaseSettings):<br>    prod_url: str<br>    dev_url: str<br><br>    class Config:<br>        env_file = &quot;./config/settings.properties&quot;</pre><h3>✅ Wrap-Up: FastAPI Microservices Architecture Summary</h3><p>✔ Break down apps with the decomposition pattern<br> ✔ Mount microservices under one gateway<br> ✔ Use a central API Gateway with redirect logic<br> ✔ Centralize logging using Loguru and middleware<br> ✔ Enable microservices to communicate via httpx and requests<br> ✔ Apply domain modeling for code clarity<br> ✔ Externalize settings with Pydantic + .env files</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92e35552a707" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Dependency Injection in FastAPI: Clean, Scalable, and Testable APIs]]></title>
            <link>https://medium.com/@azizmarzouki/mastering-dependency-injection-in-fastapi-clean-scalable-and-testable-apis-5f78099c3362?source=rss-233f593038ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f78099c3362</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Aziz Marzouki]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 14:59:40 GMT</pubDate>
            <atom:updated>2025-03-25T14:59:40.323Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One of FastAPI’s most powerful (but often underutilized) features is its native support for </em><strong><em>Dependency Injection (DI)</em></strong><em> — a design pattern that keeps your code clean, modular, and easy to test. If you’re serious about building scalable microservices, understanding DI is essential.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*I4rWjecg3dVZ8lI-.png" /></figure><p>In this article, we’ll explore how FastAPI handles DI out of the box, how to structure large projects using DI principles, and how to enhance your setup using third-party tools like <strong>Dependency Injector</strong> and <strong>Lagom</strong>.</p><h3>🔄 What Is Dependency Injection (DI)?</h3><p>Dependency Injection is a software design pattern where objects (dependencies) are provided to a class or function instead of being instantiated inside it. This creates <strong>loose coupling</strong>, making your code easier to test, maintain, and scale.</p><p>FastAPI simplifies DI by managing a container that handles the instantiation and lifecycle of dependencies — whether it’s a service class, a request validator, or even an async function.</p><h3>🛠️ Injecting Dependencies in FastAPI</h3><h4>✅ Injecting Functions</h4><p>You can create a reusable logic block (like a login creation function) and inject it into multiple routes:</p><pre>def create_login(username: str, password: str):<br>    return {&quot;username&quot;: username, &quot;password&quot;: password}<br><br>@router.get(&quot;/users/add&quot;)<br>def add_user(account=Depends(create_login)):<br>    return {&quot;user&quot;: account}</pre><h4>✅ Injecting Classes</h4><p>Classes can be treated as dependencies too:</p><pre>class AuthService:<br>    def __init__(self, secret: str):<br>        self.secret = secret<br><br>@router.post(&quot;/auth&quot;)<br>def authenticate(auth=Depends(AuthService)):<br>    return {&quot;secret&quot;: auth.secret}</pre><h3>🔗 Nested Dependencies</h3><p>FastAPI supports chaining dependencies — injecting dependencies into other dependencies. For example, a UserProfile might depend on both Login and UserDetails.</p><pre>class UserProfile:<br>    def __init__(self, login=Depends(Login), details=Depends(UserDetails)):<br>        self.login = login<br>        self.details = details<br><br>@router.post(&quot;/profile&quot;)<br>def create_profile(profile=Depends(UserProfile)):<br>    return {&quot;profile&quot;: profile.login.username}</pre><p>This modular approach leads to clean and maintainable code.</p><h3>🚀 Dependency Injection Strategies</h3><p>FastAPI supports injecting dependencies in several ways:</p><h4>✅ At the Service Level</h4><pre>@router.get(&quot;/recipes&quot;)<br>def list_recipes(service=Depends(get_recipe_service)):<br>    return service.get_all()</pre><h4>✅ At the Router Level</h4><p>Apply dependencies across all endpoints in a router:</p><pre>router = APIRouter(dependencies=[Depends(auth_check)])</pre><h4>✅ At the Global Level (main.py)</h4><p>Apply global filters like logging:</p><pre>app = FastAPI(dependencies=[Depends(log_transaction)])</pre><h3>💾 Organizing with Repository-Service Pattern</h3><p>With DI, structuring your project into <strong>model</strong>, <strong>repository</strong>, and <strong>service</strong> layers becomes natural:</p><ul><li><strong>Model</strong>: Recipe, Ingredient, etc.</li><li><strong>Repository</strong>: Handles CRUD in a database</li><li><strong>Service</strong>: Business logic that interacts with repositories</li></ul><pre>class RecipeService:<br>    def __init__(self, repo=Depends(get_recipe_repo)):<br>        self.repo = repo<br>    def get_all(self):<br>        return self.repo.fetch_all()</pre><p>This architecture keeps concerns isolated and makes your app easy to extend and test.</p><h3>📦 Using Third-Party Containers</h3><p>FastAPI’s built-in container is powerful but limited in terms of configuration. Two popular libraries help overcome this:</p><h4>✅ Dependency Injector</h4><p>Install it with pip install dependency-injector. Define a container and providers:</p><pre>from dependency_injector import containers, providers<br><br>class Container(containers.DeclarativeContainer):<br>    recipe_service = providers.Factory(RecipeService)</pre><p>Use @inject and Provide for wiring:</p><pre>@router.get(&quot;/recipes&quot;)<br>@inject<br>def get_recipes(service=Depends(Provide[Container.recipe_service])):<br>    return service.get_all()</pre><h4>✅ Lagom</h4><p>Install with pip install lagom. Easier and more lightweight:</p><pre>container = Container()<br>container[RecipeService] = RecipeService()<br><br>deps = FastApiIntegration(container)<br><br>@router.get(&quot;/recipes&quot;)<br>def get_all(service=deps.depends(RecipeService)):<br>    return service.get_all()</pre><h3>🔁 Singleton Scope</h3><p>By default, FastAPI <strong>creates a new instance</strong> for each dependency on every request. To reduce memory usage:</p><ul><li>In <strong>Dependency Injector</strong>, use Singleton():</li></ul><pre>admin_service = providers.Singleton(AdminRepository)</pre><ul><li>In <strong>Lagom</strong>, wrap with Singleton() or use request_singletons:</li></ul><pre>container[MyService] = Singleton(MyService())</pre><h3>🧠 Final Thoughts</h3><p>Dependency Injection helps FastAPI projects:</p><p>✅ Stay organized with layered architecture<br> ✅ Promote reuse of services and utilities<br> ✅ Simplify testing and mocking<br> ✅ Optimize memory and performance<br> ✅ Scale to microservices architecture</p><p>FastAPI’s DI system is already great for most apps, but with <strong>Dependency Injector</strong> or <strong>Lagom</strong>, you unlock serious flexibility for large-scale systems.</p><p>Let me know if you’d like a version focused on testing, mocking, or DI in microservices!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f78099c3362" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI Core Features: From Project Structure to Middleware Mastery]]></title>
            <link>https://medium.com/@azizmarzouki/fastapi-core-features-from-project-structure-to-middleware-mastery-b4a39b63d283?source=rss-233f593038ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4a39b63d283</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Aziz Marzouki]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 14:36:41 GMT</pubDate>
            <atom:updated>2025-03-25T14:36:41.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*HyFXWakbOf3WactC.png" /></figure><p>FastAPI is more than just a framework for building APIs — it’s a complete toolkit for modern Python web development. In this article, we’ll explore the <strong>core features</strong> of FastAPI that take you beyond simple endpoint creation and into the realm of scalable, maintainable, and production-ready microservices.</p><h3>🧱 1. Structuring a Scalable FastAPI Project</h3><p>As your FastAPI application grows, keeping things modular is key. Instead of stuffing everything in one main.py, break your app into <strong>packages</strong> and <strong>modules</strong>. Use APIRouter to define endpoints in separate files and include them in main.py.</p><p><strong>Example Project Structure</strong>:</p><pre>/project-root<br>  /login<br>    user.py<br>  /admin<br>    manager.py<br>  /places<br>    destination.py<br>  main.py</pre><p>In each module:</p><pre># login/user.py<br>from fastapi import APIRouter<br>router = APIRouter()<br><br>@router.get(&quot;/users&quot;)<br>def list_users():<br>    return {&quot;users&quot;: []}</pre><p>And in main.py:</p><pre>from fastapi import FastAPI<br>from login import user<br><br>app = FastAPI()<br>app.include_router(user.router, prefix=&quot;/api&quot;)</pre><h3>🚨 2. Exception Handling Like a Pro</h3><p>FastAPI gives you multiple ways to handle errors:</p><h4>✅ Basic Try-Except with Status Code</h4><pre>@router.put(&quot;/destination/update&quot;)<br>def update_destination(data: dict):<br>    try:<br>        # pretend logic here<br>        return {&quot;message&quot;: &quot;updated&quot;}<br>    except:<br>        return {&quot;error&quot;: &quot;destination not found&quot;}</pre><h4>✅ Raise HTTPException for precise control</h4><pre>from fastapi import HTTPException<br><br>if user_not_found:<br>    raise HTTPException(status_code=404, detail=&quot;User not found&quot;)</pre><h4>✅ Custom Exceptions + Handlers</h4><p>Create your own exception classes:</p><pre>class RatingException(HTTPException):<br>    def __init__(self, detail: str):<br>        super().__init__(status_code=403, detail=detail)</pre><p>Register custom handlers in main.py:</p><pre>@app.exception_handler(RatingException)<br>def handle_rating_error(request, exc):<br>    return JSONResponse(status_code=exc.status_code, content={&quot;error&quot;: exc.detail})</pre><h3>🔁 3. Handling Responses the Right Way</h3><p>FastAPI uses Pydantic models and JSON encoding under the hood, but sometimes you need to explicitly convert data.</p><p>Use jsonable_encoder() to serialize complex types like UUID or datetime:</p><pre>from fastapi.encoders import jsonable_encoder<br>from fastapi.responses import JSONResponse<br><br>@app.get(&quot;/tour/{id}&quot;)<br>def get_tour(id: UUID):<br>    tour = tours[id]  # suppose it&#39;s a custom object<br>    return JSONResponse(content=jsonable_encoder(tour))</pre><p>Add custom headers or cookies easily:</p><pre>return JSONResponse(<br>    content={&quot;message&quot;: &quot;done&quot;},<br>    headers={&quot;X-App-Version&quot;: &quot;1.0&quot;, &quot;Set-Cookie&quot;: &quot;token=abc123&quot;}<br>)</pre><h3>🧵 4. Running Background Tasks</h3><p>For things like logging or sending emails, you don’t want to block the response.</p><p>Use BackgroundTasks:</p><pre>from fastapi import BackgroundTasks<br><br>def log_activity(user_id: str):<br>    with open(&quot;log.txt&quot;, &quot;a&quot;) as f:<br>        f.write(f&quot;{user_id} logged in\n&quot;)<br>@app.post(&quot;/login&quot;)<br>def login(user_id: str, background_tasks: BackgroundTasks):<br>    background_tasks.add_task(log_activity, user_id)<br>    return {&quot;status&quot;: &quot;login in progress&quot;}</pre><h3>⚡ 5. Using Async Endpoints for Performance</h3><p>If you’re calling async functions (like DB queries), use async def:</p><pre>@router.get(&quot;/feedback&quot;)<br>async def get_feedback(user_id: UUID):<br>    feedback = await fetch_feedback(user_id)<br>    return feedback</pre><p>Use await only inside async functions and only with other async functions.</p><h3>🔒 6. Middleware: Filtering Requests and Responses</h3><p>Middleware lets you intercept every request/response for things like logging, auth, or header injection:</p><pre>@app.middleware(&quot;http&quot;)<br>async def log_middleware(request: Request, call_next):<br>    response = await call_next(request)<br>    response.headers[&quot;X-Processed-Time&quot;] = str(datetime.now())<br>    return response</pre><p>You can even modify the request or response before they reach the endpoint or the client.</p><h3>🧩 Summary</h3><p>This chapter takes your FastAPI skills to the next level:</p><p>✅ Organize code with routers and packages<br> ✅ Catch and customize errors gracefully<br> ✅ Return clean, encoded JSON responses<br> ✅ Offload work to background tasks<br> ✅ Use async to scale with performance<br> ✅ Build middleware for full control over request/response flow</p><p>FastAPI’s design encourages clean code, robust handling, and async-first architecture — exactly what you want when building microservices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4a39b63d283" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with FastAPI: Building REST APIs the Right Way]]></title>
            <link>https://medium.com/@azizmarzouki/getting-started-with-fastapi-building-rest-apis-the-right-way-e00b63da5ebe?source=rss-233f593038ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/e00b63da5ebe</guid>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Aziz Marzouki]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 13:58:49 GMT</pubDate>
            <atom:updated>2025-03-25T13:58:49.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/848/0*GHb-NuBrc2W9ZUxE.jpg" /></figure><p><em>In the fast-moving world of software development, choosing the right tools can define the success of your project. FastAPI, a high-performance Python framework created by Sebastián Ramírez, is quickly gaining popularity among developers who want to build efficient, scalable, and easy-to-maintain APIs. This article introduces the foundational concepts of FastAPI, walking you through setting up your development environment, defining API endpoints, and handling various types of user input — all while keeping things clean, modern, and Pythonic.</em></p><h3>1. Setting Up the Environment</h3><p>FastAPI runs on Python 3.6 or higher and pairs nicely with an ASGI server like <strong>Uvicorn</strong> for handling asynchronous requests. Here’s a quick setup checklist:</p><ul><li>Install Python 3.8+</li><li>Use an editor like <strong>Visual Studio Code</strong> (with Python extensions installed)</li><li>Install FastAPI and Uvicorn:</li></ul><pre>python -m pip install --upgrade <br>pip pip install fastapi <br>pip install uvicorn[standard] <br>pip install python-multipart bcrypt</pre><p>Optional: pip install fastapi[all] installs extra dependencies.</p><h3>2. Building a Basic FastAPI App</h3><p>You start by creating a main.py file and defining your app:</p><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/hello&quot;)<br>def read_root():<br>    return {&quot;message&quot;: &quot;Hello, FastAPI!&quot;}</pre><p>Run it with:</p><pre>uvicorn main:app --reload</pre><p>Visit <a href="http://localhost:8000/docs">http://localhost:8000/docs</a> to access the built-in Swagger UI.</p><h3>3. Defining RESTful Endpoints</h3><p>FastAPI uses decorators to define HTTP methods:</p><ul><li><strong>GET</strong>: Fetch data</li><li><strong>POST</strong>: Create new data</li><li><strong>PUT</strong>: Replace existing data</li><li><strong>PATCH</strong>: Partially update data</li><li><strong>DELETE</strong>: Remove data</li></ul><h4>Example: A Simple Book API</h4><pre>from uuid import UUID<br>from typing import Dict<br>from fastapi import FastAPI<br><br>app = FastAPI()<br>books = {}<br><br>@app.post(&quot;/books/&quot;)<br>def add_book(title: str, author: str):<br>    book_id = str(UUID(int=UUID().int % 1_000_000))<br>    books[book_id] = {&quot;title&quot;: title, &quot;author&quot;: author}<br>    return {&quot;book_id&quot;: book_id}</pre><p>You can also use <strong>Pydantic models</strong> to structure request and response bodies.</p><h3>4. Handling Requests: Parameters and Bodies</h3><p>FastAPI is smart about parsing input:</p><ul><li><strong>Path parameters</strong> (/items/{id}): required and type-checked</li><li><strong>Query parameters</strong> (/search?q=term): optional or required</li><li><strong>Request bodies</strong> (for POST, PUT, PATCH): defined using BaseModel</li><li><strong>Form data</strong>: handled using Form(...)</li><li><strong>Cookies</strong> and <strong>headers</strong>: managed with Cookie() and Header()</li></ul><h4>Example: Creating a User</h4><pre>from pydantic import BaseModel<br>from uuid import uuid4<br><br>class User(BaseModel):<br>    username: str<br>    password: str<br><br>users = {}<br><br>@app.post(&quot;/users/register&quot;, response_model=User)<br>def register_user(user: User):<br>    user_id = str(uuid4())<br>    users[user.username] = {&quot;id&quot;: user_id, **user.dict()}<br>    return user</pre><h3>5. Default and Optional Parameters</h3><p>You can make parameters optional or assign default values easily:</p><pre>from typing import Optional<br><br>@app.get(&quot;/search&quot;)<br>def search_items(query: Optional[str] = None):<br>    return {&quot;result&quot;: f&quot;Searching for {query or &#39;everything&#39;}&quot;}</pre><h3>6. Nested Models and Complex Objects</h3><p>FastAPI allows deeply nested models using Pydantic. For example:</p><pre>from typing import List<br>from datetime import date<br><br>class Comment(BaseModel):<br>    text: str<br>    date_posted: date<br><br>class BlogPost(BaseModel):<br>    title: str<br>    content: str<br>    comments: List[Comment]</pre><h3>7. Cookies and Headers</h3><p>You can read or write cookies and headers easily:</p><pre>from fastapi import Cookie, Header, Response<br><br>@app.post(&quot;/session/create&quot;)<br>def create_session(response: Response):<br>    response.set_cookie(key=&quot;session_token&quot;, value=&quot;abc123&quot;)<br>    return {&quot;message&quot;: &quot;Session created&quot;}<br><br>@app.get(&quot;/session&quot;)<br>def read_session(session_token: str = Cookie(None)):<br>    return {&quot;session_token&quot;: session_token}</pre><h3>8. Summary</h3><p>FastAPI simplifies building APIs by embracing Python’s type hints and automating documentation with tools like OpenAPI. This chapter shows that even a beginner can quickly get up and running with features that usually take extra effort in other frameworks.</p><p>Whether you’re building a discussion forum, a bookstore, or a todo app, FastAPI lets you focus on the logic without drowning in boilerplate. Next, you can dive deeper into middleware, async operations, and dependency injection to build full-scale microservices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e00b63da5ebe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing in Java using JUnit and Mockito]]></title>
            <link>https://medium.com/@azizmarzouki/unit-testing-in-java-using-junit-and-mockito-79949e1c288f?source=rss-233f593038ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/79949e1c288f</guid>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[unittest]]></category>
            <dc:creator><![CDATA[Aziz Marzouki]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 22:24:34 GMT</pubDate>
            <atom:updated>2024-11-05T22:24:34.220Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s a quick cheat sheet for unit testing in Java using <strong>JUnit</strong> and <strong>Mockito</strong>. This covers the essentials for setting up and running tests, mocking dependencies, and verifying interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*gTlHmhH_aLwYJKd4.png" /></figure><h3>1. Setting Up Dependencies</h3><p>Make sure you have JUnit and Mockito in your build file:</p><h3>Maven</h3><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;<br>    &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;<br>    &lt;version&gt;5.9.0&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.mockito&lt;/groupId&gt;<br>    &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;<br>    &lt;version&gt;5.0.0&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><h3>Gradle</h3><pre>testImplementation &#39;org.junit.jupiter:junit-jupiter-engine:5.9.0&#39;<br>testImplementation &#39;org.mockito:mockito-core:5.0.0&#39;</pre><h3>2. Basic JUnit 5 Annotations</h3><ul><li><strong>@Test</strong> — Marks a method as a test method.</li><li><strong>@BeforeEach</strong> — Runs before each test; use it for common setup.</li><li><strong>@AfterEach</strong> — Runs after each test; use it for cleanup.</li><li><strong>@BeforeAll</strong> — Runs once before all tests (static method).</li><li><strong>@AfterAll</strong> — Runs once after all tests (static method).</li><li><strong>@Disabled</strong> — Ignores/skips a test.</li></ul><h3>Example</h3><pre>import org.junit.jupiter.api.*;<br>class MyTests {<br>    @BeforeEach<br>    void setup() {<br>        // Code to run before each test<br>    }<br>    @Test<br>    void testSomething() {<br>        Assertions.assertEquals(2, 1 + 1);<br>    }<br>    @AfterEach<br>    void tearDown() {<br>        // Code to run after each test<br>    }<br>}</pre><h3>3. Assertions</h3><h3>Common JUnit Assertions</h3><pre>Assertions.assertEquals(expected, actual);<br>Assertions.assertTrue(condition);<br>Assertions.assertFalse(condition);<br>Assertions.assertNull(object);<br>Assertions.assertNotNull(object);<br>Assertions.assertThrows(Exception.class, () -&gt; {<br>    // code that throws exception<br>});</pre><h3>4. Mocking with Mockito</h3><h3>Basic Annotations</h3><ul><li><strong>@Mock</strong> — Create a mock instance.</li><li><strong>@InjectMocks</strong> — Inject mock instances into the tested object.</li><li><strong>@Spy</strong> — Create a partial mock, allowing real method calls.</li><li><strong>@Captor</strong> — Capture arguments for further assertions.</li></ul><h3>Example Setup</h3><pre>import org.mockito.*;<br>import org.junit.jupiter.api.BeforeEach;<br>import org.junit.jupiter.api.Test;<br>import static org.mockito.Mockito.*;<br>class MyServiceTest {<br>    @Mock<br>    private Dependency dependency;<br>    @InjectMocks<br>    private MyService service;<br>    @BeforeEach<br>    void init() {<br>        MockitoAnnotations.openMocks(this);<br>    }<br>}</pre><h3>5. Stubbing and Verifying</h3><h3>Stubbing Methods</h3><pre>when(dependency.someMethod()).thenReturn(&quot;mockedValue&quot;);<br>when(dependency.someMethod()).thenThrow(new Exception(&quot;error&quot;));<br>doReturn(&quot;value&quot;).when(dependency).anotherMethod();</pre><h3>Verifying Interactions</h3><pre>verify(dependency).someMethod();<br>verify(dependency, times(2)).someMethod();<br>verify(dependency, never()).someMethod();<br>verify(dependency, atLeastOnce()).someMethod();<br>verifyNoMoreInteractions(dependency);</pre><h3>6. Argument Matching</h3><h3>Basic Matchers</h3><pre>when(dependency.someMethod(anyString())).thenReturn(&quot;mockedValue&quot;);<br>when(dependency.someMethod(eq(&quot;exactValue&quot;))).thenReturn(&quot;mockedValue&quot;);</pre><h3>Capturing Arguments</h3><pre>@Captor<br>ArgumentCaptor&lt;String&gt; captor;<br><br>@Test<br>void testCaptor() {<br>    service.doSomething(&quot;test&quot;);<br>    verify(dependency).someMethod(captor.capture());<br>    Assertions.assertEquals(&quot;test&quot;, captor.getValue());<br>}</pre><h3>7. Advanced Mockito Techniques</h3><h3>Using Spies for Partial Mocks</h3><pre>@Spy<br>private MyService serviceSpy;<br><br>@Test<br>void testSpy() {<br>    doReturn(&quot;mockedResult&quot;).when(serviceSpy).someMethod();<br>    Assertions.assertEquals(&quot;mockedResult&quot;, serviceSpy.someMethod());<br>}</pre><h3>Mocking Static Methods (Requires Mockito v3.4+ with Mockito-inline)</h3><pre>import static org.mockito.Mockito.mockStatic;<br><br>@Test<br>void testStaticMock() {<br>    try (MockedStatic&lt;SomeStaticClass&gt; mocked = mockStatic(SomeStaticClass.class)) {<br>        mocked.when(SomeStaticClass::someMethod).thenReturn(&quot;mockedValue&quot;);<br>        Assertions.assertEquals(&quot;mockedValue&quot;, SomeStaticClass.someMethod());<br>    }<br>}</pre><h3>8. Exception Handling</h3><h3>Asserting Exceptions</h3><pre>@Test<br>void testException() {<br>    Exception exception = Assertions.assertThrows(IllegalArgumentException.class, () -&gt; {<br>        service.methodThatThrows();<br>    });<br>    Assertions.assertEquals(&quot;Expected message&quot;, exception.getMessage());<br>}</pre><h3>9. Tips</h3><ul><li><strong>Use </strong><strong>@ExtendWith(MockitoExtension.class)</strong> for JUnit 5 if you prefer instead of MockitoAnnotations.openMocks(this).</li><li><strong>Clear interactions</strong>: clearInvocations(dependency); to reset invocation history on a mock.</li><li><strong>Reset mocks</strong> after each test if reusing them: reset(dependency);.</li></ul><p>This cheat sheet should cover most scenarios when using JUnit and Mockito together for unit testing in Java.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79949e1c288f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>