Here’s an analogy to understand the answer. In villages, grain is often stored in huge vertical containers; fresh grain is poured into the top, and old stored grain is taken out from the bottom. A farmer may have produced poor quality grain of, say, brand Z for the past four years and stocked it in his container. This year he produces high quality grain of, say, brand A and stores it at the top. He is therefore exasperated when he finds grain of brand Z coming out from the bottom. This illustrates how seemingly innocent people suffer in this life: they have been doing good things in this life, but have earlier done bad things whose reactions are coming to them now.
The workings of karma are often difficult to appreciate is that most people have a karmic record that is neither white nor black, but shades of gray. That mixed record leads to reactions that often appear arbitrary. A question that vexes many when they see bad things happening to good people is: “If these people were really so bad in their earlier lives, how could they have been virtuous in this life for so long?”
There are several possible answers. We often see even upright people occasionally succumbing to temptation and perpetrating abominable misdeeds. Of course, their virtuous nature rectifies them quickly, but still the fact remains that they did commit a greatly sinful act and are therefore liable for a reaction. So the wrongdoing, like an ugly black spot on their otherwise clean karmic slate, will result in a severe reaction in an otherwise happy future life. Shift this scenario one lifetime backwards and we have the answer to the above question. The harsh affliction coming to a good person may thus be due to an occasional but grave transgression in a previous life.
Also, our behavior in this life is not determined only by our tendencies in the previous life; upbringing and association in this life also play a significant role. So if people with bad inclinations are born into a good family because of some good karma, their congenial upbringing and surroundings may empower them to shed their baggage of negative propensities. Thus they may become moral in this life, but their misdeeds from previous lives will make them suffer despite their rectified conduct now.
Thus the principles of reincarnation allow us to view life with a much broader perspective—not from the standpoint of one brief lifetime, which is nothing more than a flash in time, but from the standpoint of eternity. With this broader vision we can understand how each of us individual souls is alone responsible for what happens in our life.
No doubt, the issue of karmic justice is complex and one short answer can’t do justice to it.