Empirically, net capital inflows are pro-cyclical in developed countries and counter-cyclical in developing countries. That said, private inflows are pro-cyclical and public inflows are counter-cyclical in both groups of countries. The dominance of private (public) inflows in developed (developing) countries drives the difference in total net inflows. We rationalize these patterns using a dynamic stochastic two-sector model of a small open economy facing borrowing constraints. Private agents over-borrow because of the pecuniary externality arising from constraints. The government saves abroad to reduce aggregate debt, making the economy resilient to adverse shocks. Differences in borrowing constraints and shock processes across countries explain the empirical patterns of capital inflows.