We characterize optimal unemployment insurance (UI) in a heterogeneous-agent model with unemployment risk and sticky prices . In the long run, the optimal reform calls for a lower replacement rate that raises vacancies and lowers unemployment. In the short run, the optimal reform raises the replacement rate initially to smooth real wage adjustments along the transition and attenuate short-run welfare losses. Once at its optimal level, the replacement rate should vary counter-cyclically in response to demand shocks. Productivity shocks generate quasi-efficient fluctuations and call for a quasi-constant replacement rate. The aggregate welfare gains from an optimal reform are large, around 1% of equivalent consumption. The aggregate welfare gains from an optimal UI policy over the business cycle are smaller, around 0.2%, and essentially vanish with flexible prices because the aggregate demand stabilization motive is muted.