Immunity is long-lasting because some of the many kinds of cells that make up the normal human immune system are naturally able to retain a “memory” of the defense efforts aroused by certain infections or vaccines.
There are many kinds of immune cells, including T cells and different types of white cells. Their interaction with disease is complex and involves long chains of interactions and responses.
A vaccine fools the body into thinking it is being infected and creating a defense against that organism that it keeps in its immune memory. Later, if exposed to the infection, the body fights it quickly.
For example, after an actual infection with a disease like measles, which people rarely get more than once, immune memory is created, and certain cells are ready to fight again upon reexposure. The memory remains for years.
For some vaccines, protection may last a long time, even a lifetime. But for others, vaccines may protect for only a short time.