What is a reentrancy attack and how do you prevent it?
What the interviewer wants to hear
- External call gives control to another contract before state is updated
- Attacker re-enters and repeats the action, such as withdrawing again
- Checks-effects-interactions pattern
- Reentrancy guards (nonReentrant)
- Pull payments and awareness of cross-function and read-only reentrancy
Model answer
Reentrancy happens when a contract makes an external call, for example sending ETH, before it finishes updating its own state. The receiver is a contract whose receive or fallback function calls back into the original function. Because the balance has not been set to zero yet, the attacker withdraws again and again. This was the cause of The DAO hack in 2016. The main defence is the checks-effects-interactions pattern: first validate inputs, then update state, and only then make external calls. I also add a reentrancy guard like OpenZeppelin's nonReentrant, or the transient storage version, on functions that move funds. Reentrancy can also cross functions, where the attacker re-enters a different function that shares state, or be read-only, where another protocol reads a stale view. Pull payment patterns and careful handling of token callbacks, like ERC-777 or ERC-721 safeTransfer hooks, also reduce risk.
Can you answer it under time pressure?
Take a timed medium round and get scored on every answer.
More medium Blockchain Developer questions
- What techniques do you use to reduce gas costs in Solidity contracts?
- How do you test a smart contract before deploying it to mainnet?
- How do upgradeable smart contracts work, and what are the trade-offs?
- What is a blockchain oracle and how do you use price data safely?
- How do signature-based approvals like ERC-2612 permit and Permit2 work, and what are their risks?
- How do you build a reliable dApp frontend that reads and writes contracts with viem and wagmi?
- How do chain reorganizations affect a dApp or backend service, and how do you handle them?
- How do you design admin control for a protocol so it can be maintained without making users trust a single person?
- Walk me through how you deploy a set of contracts to mainnet safely.