Immunological memory is the reason surviving a disease usually protects against getting it again, and the reason vaccination works at all. It is among the best established mechanisms in biology and it was exploited successfully for centuries before anyone understood it.
An immune response to a new pathogen is slow, taking days to a week, because the few cells whose receptors happen to match must find the invader, multiply, and mature. Most of that expanded population dies once the infection clears. A fraction persists as memory cells.
Memory changes three things. The responding population is far larger to begin with. Memory B cells have already undergone affinity maturation, so their antibodies bind the target far more tightly than the originals did. And memory cells respond faster, often clearing a repeat infection before symptoms appear. Long-lived plasma cells, meanwhile, sit in the bone marrow secreting antibody continuously for years or decades without further stimulation.

Duration varies enormously by pathogen, which is why some vaccines are lifelong and others are annual, and the difference is a property of the pathogen rather than a failure of the vaccine.
Antibody responses to smallpox and yellow fever vaccination persist for decades, and a study of people vaccinated against smallpox found measurable responses more than fifty years later. Measles immunity is effectively lifelong. Tetanus and diphtheria require boosting roughly every decade. Influenza and coronaviruses require repeated vaccination for two separate reasons that are often confused: waning of the response, and antigenic change in the pathogen itself, so that the memory is intact but no longer matches.
Several strategies exist. Antigenic variation, where the pathogen changes the surfaces memory recognises, is used by influenza through drift and shift and by trypanosomes through wholesale surface switching. Latency allows herpesviruses to persist where the immune system cannot reach. Direct attack on immune memory is the strategy of HIV, and measles does something particularly striking: it depletes existing memory cells, producing an immune amnesia that leaves a recovered child more vulnerable to other infections for years, which is an under-appreciated argument for vaccination against it.

The classical account held that only the adaptive system remembers. Work over the past fifteen years has established that innate cells can also be reprogrammed by exposure, through epigenetic changes that leave them responding more strongly to later, unrelated challenges. This is called trained immunity and it offers an explanation for long-observed non-specific benefits of some vaccines, notably BCG. It extends the concept of memory rather than overturning it, and how long it lasts and how much it matters clinically are still being worked out.