1. Gesetzliche Rentenversicherung (statutory pension)
Contributions are credited to your German pension account regardless of where you live in retirement. The pension itself is paid out wherever you reside, with some technical rules around bank accounts and proof of life.
Inside the EU/EEA/Switzerland: contributions in different member states are aggregated under EU regulation 883/2004, no contributions are 'lost', and the minimum vesting period can be met across countries.
Outside the EU: depends on whether Germany has a social-security agreement (Sozialversicherungsabkommen) with the country. With agreement: similar logic to EU. Without agreement: you only collect what you funded yourself; you can sometimes claim a one-off reimbursement of your contributions after at least 24 months outside the EU.