How Does DeFi Work? A Technical Breakdown of the Mechanics
Most explainers stop at "no banks." This one goes deeper: how DeFi actually works at the level of smart contracts, AMM pricing math, liquidity pools, price oracles, composability, and on-chain settlement, plus where each piece tends to break.

If you want to understand how does DeFi work beyond the marketing, you have to look at what executes when you click "swap" or "supply." Decentralized finance is not a single app or company. It is a stack of programs running on a shared, public ledger, where the rules of a lending market or an exchange live in deployed code rather than in a bank's back office. Every position, trade, and interest accrual is a state change recorded on-chain and reproducible by anyone running the same node software.
This piece is the mechanics version. We skip the "it's like a bank but on blockchain" framing and walk through the actual moving parts: the contracts that hold the money, the math that prices a trade, the data feeds that decide when you get liquidated, and the settlement layer that makes all of it final.
The settlement layer is the thing that makes it real
Before any DeFi logic runs, something has to agree on state. That something is the base blockchain, usually Ethereum or an EVM-compatible chain. The blockchain does one job that matters here: it gives every participant the same ordered history of transactions, so two people can't spend the same dollar twice and no single party can quietly rewrite the ledger.
A transaction is a signed message. You sign it with your private key, broadcast it to the network, and validators include it in a block. Once that block is finalized, the state change is settled. There is no "pending review" queue staffed by a human, and there is no Monday-morning batch. The protocol either accepts the transaction and updates state, or it reverts and you keep your funds minus gas.
Gas is the part people underestimate. Every operation a contract performs costs gas, paid in the chain's native token. A simple transfer is cheap. A multi-step swap that touches three contracts and updates a dozen storage slots is not. Gas is both the spam-prevention mechanism and the reason DeFi UX has historically been rough: a $4 trade can carry a $30 settlement cost when the network is congested. Layer-2 rollups exist largely to push that cost down by settling many transactions to the base chain in compressed batches.
In DeFi, "the system" is a set of public programs. There is no operator you can call, and no operator who can quietly bail you out. The code that holds your money is the same code anyone can read.
How does DeFi work at the contract level
The core abstraction is the smart contract: a program deployed to an address on the chain. It has storage (its memory), functions (the things it can do), and a balance (tokens it holds). Crucially, it custodies funds itself. When you deposit into a lending market, you are not handing assets to a company. You are calling a function that moves your tokens into a contract's balance and credits you a claim in that contract's storage.
Three properties drive everything downstream:
- Deterministic execution. Given the same input and the same chain state, a contract produces the same result every time, on every node. This is what lets the whole network agree on outcomes without trusting a referee.
- Public and immutable by default. The deployed bytecode is visible, and unless the developers built in an upgrade mechanism, it cannot be changed. That is a feature for trust and a liability when there is a bug.
- Composability. A contract can call another contract mid-transaction. This is the property that makes the rest of the article possible, and it is covered in its own section below.
The flip side of deterministic, immutable code is that mistakes are permanent and exploitable. A reentrancy bug or a flawed access-control check is not a support ticket; it is a drained pool. Most serious losses in this space trace back to contract logic, not to the blockchain itself, which is why disciplined teams treat audits, invariant testing, and formal verification as non-negotiable. We go deeper into that engineering discipline in our write-up on building and securing DeFi smart contracts.
Liquidity pools and the end of the order book
Traditional exchanges match a buyer with a seller through an order book. That model needs market makers constantly posting bids and asks, and it needs a fast, centralized engine to match them. On a blockchain where every state change costs gas and settles in seconds, a classic order book is impractical for most assets.
DeFi solved this with the liquidity pool. Instead of matching individuals, a pool is a single contract holding a reserve of two (or more) tokens. Anyone can become a liquidity provider by depositing both assets in the required ratio. In return they receive LP tokens, which represent their share of the pool and entitle them to a cut of trading fees.
When you trade, you don't wait for a counterparty. You trade against the pool. You add token A, the pool gives you token B, and the reserve ratios shift. The pool is always available, which is the entire point: liquidity is pooled and passive rather than actively quoted.
There is a cost to providing liquidity that catches newcomers: impermanent loss. When the external market price of the paired assets diverges, arbitrageurs rebalance the pool, and an LP can end up worse off than if they had simply held the two tokens. Fees are meant to compensate for this, but they don't always.
AMMs and the math that sets the price
A liquidity pool needs a rule for how much token B to give you for your token A. That rule is the automated market maker, or AMM. The most common is the constant product formula:
x * y = k
Here x and y are the pool's reserves of the two tokens, and k is a constant. Every trade must keep the product k unchanged (before fees). If you remove some token B, you must add enough token A to hold x * y constant. The price you get falls directly out of this equation, no human quoting required.
Two consequences follow from this design, and both matter in practice:
- Slippage scales with trade size relative to pool depth. A small trade against a deep pool barely moves the ratio, so your price is close to the spot rate. A large trade against a thin pool moves
xandya lot, and you pay a worse average price. This is why deep liquidity is so valuable and why thin pools are dangerous to trade in size. - The AMM doesn't know the "real" price. It only knows its own reserves. It relies on arbitrageurs to bring the pool's implied price back in line with the wider market whenever it drifts. That arbitrage is a feature, not a bug, but it is also what funds impermanent loss for LPs.
Newer designs refine this. Concentrated liquidity lets providers focus their capital in a price range where trading actually happens, improving capital efficiency dramatically. Stablecoin-focused AMMs use curves tuned for assets that should trade near a 1:1 ratio. The constant-product model is the foundation, not the ceiling.
Oracles: how a closed system learns the outside price
A blockchain is deliberately isolated. Contracts can read on-chain state, but they cannot natively fetch the price of ETH from an exchange or check whether a loan's collateral is still solvent. That isolation is what keeps execution deterministic. It is also a problem the moment your protocol needs to know a real-world number.
Oracles bridge that gap. An oracle is a service that writes external data onto the chain in a form contracts can read. A lending protocol uses a price oracle to decide when a borrower's collateral has fallen below the required threshold and the position should be liquidated. A derivatives protocol uses one to mark positions to market.
The oracle is one of the most security-critical components in the entire stack, because a contract trusts the number it reads. If an attacker can manipulate the reported price, even briefly, they can trigger unfair liquidations or borrow against collateral the protocol misvalues. A recurring class of exploits works exactly this way: use a flash loan to distort a thin on-chain pool, feed that distorted price to a protocol that naively reads it, and walk away with the difference. The defenses, time-weighted average prices, multiple independent data sources, and aggregated feeds, all exist because of that attack surface. Designing oracle integration correctly is one of the harder parts of any production deployment, and it is a core concern for any serious blockchain development team shipping financial contracts.
Composability: why DeFi is a system, not a list of apps
This is the property that turns a pile of separate contracts into something genuinely new. Because contracts can call each other within a single atomic transaction, protocols snap together like building blocks. The industry's nickname for this, "money legos," is glib but accurate.
A single transaction can do all of the following and either complete fully or revert entirely:
- Borrow an asset from a lending market
- Swap it on an AMM
- Deposit the result into a yield strategy
- Use the resulting position as collateral somewhere else
Atomicity is the unsung hero here. If any step fails, the whole transaction unwinds as if it never happened. That is what makes flash loans possible: you can borrow millions with zero collateral, provided you repay within the same transaction, because if you don't, the borrow itself reverts.
Composability is also why DeFi compounds risk. When protocol B builds on protocol A, a flaw or a price dislocation in A propagates into B, and into anything built on B. A stablecoin depeg or an oracle failure rarely stays contained. The same interconnection that creates capital efficiency creates correlated failure. We explore that systemic angle, and where the model is heading, in our look at DeFi and the future of decentralized finance.
Putting one transaction together end to end
Trace a single leveraged-deposit action to see how the pieces interact:
- You sign and submit. Your wallet signs a transaction calling a contract function and broadcasts it. Gas is reserved.
- The lending contract runs. It checks your collateral against the oracle price, confirms you're within limits, and credits you a borrowed balance from its reserves.
- A swap executes against an AMM. The borrowed token routes through a liquidity pool; the constant-product math sets your output amount, and slippage is checked against your limit.
- The output is redeposited as collateral, increasing your exposure. Your position now spans two protocols.
- The block finalizes. Every state change settles at once. If any step had failed, the entire sequence would have reverted and you'd have lost only gas.
No bank cleared anything. No counterparty was matched by a human. The "institution" was four contracts and a price feed, executing in order, atomically, in public.
What actually breaks, and why it matters
The mechanics are elegant, but the failure modes are specific and worth naming plainly:
- Contract bugs. Reentrancy, bad access control, arithmetic errors. Immutable code means a shipped bug is a standing liability.
- Oracle manipulation. A protocol is only as honest as the price it reads.
- Economic design flaws. Incentives that look fine in isolation can collapse under stress, especially around stablecoin pegs and liquidation cascades.
- Composability contagion. One protocol's failure becomes everyone's failure when they're stacked.
None of this is an argument against DeFi. It is an argument for treating it as serious financial infrastructure built in an adversarial environment, where the threat model includes every other participant on the chain. For a broader view of how this category grew from an experiment into a movement, our overview of DeFi as a trend in the crypto world puts the mechanics in context.
Understanding how DeFi works means holding both halves at once: the design is genuinely powerful, and the same properties that make it powerful, public code, deterministic execution, and composability, are exactly the ones that punish sloppy engineering. The teams that ship durable systems are the ones that respect both.
Frequently asked questions
DeFi replaces intermediaries with smart contracts: programs deployed on a blockchain that custody funds and execute rules automatically. When you lend, borrow, or trade, you call a contract function that moves tokens and updates on-chain state. The blockchain settles the result, so no company approves, clears, or holds your assets.
A liquidity pool is a smart contract holding reserves of two or more tokens that traders trade against instead of waiting for a counterparty. Liquidity providers deposit assets and earn a share of trading fees. An automated market maker formula, often constant product (x times y equals k), sets prices directly from the pool's reserve balances.
Oracles bring external data, mostly asset prices, onto the blockchain so contracts can read it. Lending protocols use price oracles to decide when collateral falls below the liquidation threshold. Because contracts trust the number they read, oracles are highly security-critical: a manipulated price can trigger unfair liquidations or drain funds.
Composability lets contracts call each other within one atomic transaction, so protocols combine like building blocks. A single transaction can borrow, swap, and redeposit, and either fully completes or reverts. This enables flash loans and complex strategies, but it also spreads risk: a flaw in one protocol can propagate to everything built on top of it.
The biggest risks are smart contract bugs, oracle manipulation, flawed economic incentives, and composability contagion where one protocol's failure cascades into others. Because deployed code is often immutable, a shipped bug becomes a permanent liability. This is why audits, invariant testing, and careful oracle design are essential for production systems.
Gas is the fee paid in a chain's native token for every computational step a contract performs. Simple transfers are cheap; multi-step DeFi actions touching several contracts cost more. Gas prevents spam and prices network demand, which is why congestion can make small trades expensive. Layer-2 rollups exist largely to reduce these settlement costs.
More from the journal

Smart Contract Audit: What It Is, the Process, and Costs
A smart contract audit is the last gate before mainnet for code that can't be patched and holds real money. This guide covers what an audit checks, how the process and timeline work, what it costs, and how to prepare your contracts so reviewers find design flaws, not typos.

DeFi Smart Contracts: Patterns, Pitfalls, and Audits
DeFi smart contracts hold real money on public infrastructure where one logic flaw can drain a protocol in a single block. This guide covers the patterns that move that money, the bugs that lose it, and the audit-first process that keeps it where it belongs.

Smart Contract Development: The Full Lifecycle, Explained
Smart contract development is more than writing Solidity. This guide walks the full lifecycle, from specification through fuzzing, audit, deployment, and monitoring, and shows where automated on-chain logic actually pays off for a business.