# The Constant Product AMM Invariant: A Deep Dive for Protocol Builders

> Understand the x*y=k AMM invariant at the implementation level — price impact, LP math, fee integration, and where the model breaks down in production DeFi.

- **Published:** 2026-05-07
- **Author:** Clixo
- **Reading time:** 6 min read
- **Tags:** amm, defi, protocol-design, liquidity, market-making
- **Canonical URL:** https://clixo.sh/blog/constant-product-amm-invariant-deep-dive

Every DeFi engineer has heard of x\*y=k. Far fewer can explain what happens to the invariant when fees are added, why LP shares are not priced linearly, or where the model fails in production. If you are building on top of or extending a constant-product AMM, these details determine whether your integration is correct.

## The Core Invariant

A constant-product pool holds two tokens, `x` and `y`. After every swap, the product of the reserves must remain equal to a constant `k`:

```
x * y = k
```

If a trader wants to receive `dy` of token Y, they must deposit enough token X to preserve the invariant. Given reserves `x` and `y`:

```
(x + dx) * (y - dy) = x * y
dx = x * dy / (y - dy)
```

This is why slippage increases for larger trades — as `dy` approaches `y`, `dx` grows asymptotically. The AMM never runs out of the output token; it just prices it progressively higher.

## Price and Price Impact

The marginal price of token Y in terms of token X at any moment is:

```
P = x / y
```

This is the instantaneous exchange rate. After a trade of size `dy`, the new price is:

```
P_new = (x + dx) / (y - dy)
```

Price impact — how much the trade moves the price — depends entirely on the ratio of `dy` to `y`. A trade that takes 1% of the Y reserve moves the price approximately 2% (the exact calculation requires the full invariant math). This is the source of the common approximation that slippage doubles for each doubling of trade size relative to pool depth.

For protocol builders integrating AMM prices: never use the current reserves to compute a price for risk management. The spot price is trivially manipulable in a single block. Use a TWAP.

## How Fees Work With the Constant Product AMM Invariant

Standard AMMs do not hold `k` perfectly constant — they allow `k` to grow slightly over time as fees accumulate. The most common implementation applies a fee to the input before computing the output:

```
dx_with_fee = dx * (1 - fee)
dy = y * dx_with_fee / (x + dx_with_fee)
```

With a 0.3% fee, only 99.7% of the input counts toward the swap computation. The remaining 0.3% stays in the pool, increasing `k`. Over time, this fee growth is what makes LP positions profitable even in the absence of external rewards.

The LP share of fee accrual is passive — fees simply inflate the reserves, so each LP share represents a growing fraction of a growing pool.

```mermaid
sequenceDiagram
  participant T as Trader
  participant P as Pool
  participant R as Reserves
  T->>P: deposit dx tokens
  P->>P: apply fee (dx_with_fee = dx * 0.997)
  P->>P: compute dy via x*y=k invariant
  P->>R: add 0.3% fee to reserves
  P->>T: release dy tokens
  R->>R: k grows slightly
```

## LP Shares: Minting and Burning

When liquidity is added, the protocol mints shares proportional to the contribution. For the first deposit, shares are typically set to `sqrt(dx * dy)` to avoid bias toward either token. Subsequent deposits use:

```
shares = min(dx / x_total, dy / y_total) * totalShares
```

The `min` ensures that LPs who provide imbalanced amounts do not receive shares that would dilute existing LPs. Any excess tokens above the required ratio are either refunded or the user is required to provide a balanced deposit.

When shares are burned, the LP receives:

```
dx_out = (shares / totalShares) * x_total
dy_out = (shares / totalShares) * y_total
```

Because fees have accumulated since the LP deposited, `dx_out` and `dy_out` will be greater in aggregate value than the original deposit — assuming no impermanent loss offset.

## Impermanent Loss: The Real Cost for LPs

When the price ratio between the two tokens changes after an LP deposits, the LP's position at withdrawal is worth less than simply holding the tokens. This is **impermanent loss** (IL). The formula for IL as a function of price ratio change `r`:

```
IL = 2 * sqrt(r) / (1 + r) - 1
```

Where `r` is the ratio of the new price to the original price. A 2x price move causes approximately 5.7% impermanent loss. A 5x move causes approximately 25% IL.

The loss is "impermanent" only in the sense that it reverses if the price returns to the entry ratio. If the price never returns, the loss is permanent. LPs are profitable when fee revenue exceeds accumulated IL — which requires high trading volume relative to pool size and low price volatility.

## Where the Constant Product Model Breaks Down

**Stablecoin pairs.** For assets that trade within a narrow range, x\*y=k wastes most of the liquidity in price ranges that never trade. The StableSwap invariant (Curve's formula) concentrates liquidity near the peg and is superior for stablecoin-to-stablecoin swaps.

**Correlated assets.** For wBTC/renBTC or stETH/ETH, the constant product curve still spreads liquidity across an unrealistically wide range. Protocols like Curve's crypto pools or custom invariants handle this better.

**Low-liquidity tokens.** For tokens with thin AMM pools, the constant product formula provides essentially no price stability — a small trade can move the price dramatically. These pools are not appropriate as price sources for any risk management system.

**Gas optimization.** Each swap requires reading reserves, computing outputs, and updating state. On L1, this is expensive. On L2s with cheap calldata, it is manageable, but batch swap routing across multiple pools still requires careful engineering to stay within block gas limits.

## Extending the Constant Product AMM

Many production protocols extend the basic model rather than replacing it:

- **Dynamic fees:** Adjust fee rates based on volatility to better compensate LPs during high-IL periods
- **Range orders:** Concentrated liquidity (Uniswap V3) allows LPs to target specific price ranges, effectively implementing limit orders through AMM mechanics
- **Single-sided liquidity:** Some protocols allow depositing only one token, using the AMM to balance the position over time
- **Protocol fees:** A fraction of the swap fee routes to a protocol treasury rather than LPs, creating sustainable protocol revenue

Each extension adds complexity to the invariant math and requires careful auditing of edge cases.

---

Understanding the invariant deeply is what separates engineers who copy a reference implementation from those who can reason about edge cases, design extensions, and catch bugs before audit. If you are building an AMM or integrating one into your protocol, [Clixo's DeFi engineering team](https://clixo.sh/#contact) can help you ship it correctly.

---

Clixo · 1141 W Bryn Mawr Ave, Itasca, IL 60143, US · [hello@clixo.sh](mailto:hello@clixo.sh)
[Start a build](https://clixo.sh/#contact) · [All services](https://clixo.sh/services) · [Agent guide (llms.txt)](https://clixo.sh/llms.txt)
