https://ohr.edu/explore_judaism/ask_the_rabbi/ask_the_rabbi/5321
From: Jonathan
Dear Rabbi,
I read that G-d remembers good deeds for thousands of generations. However, the bad deeds of the current generation are carried onward for three or four generations. This infliction on those who are yet unborn or on those who are not directly responsible for the bad deeds does not seem right to me. Perhaps you could provide some positive thoughts. Thank you and best regards.
Dear Jonathan,
I agree with you that punishing innocents for crimes that others have committed doesn't seem fair. The Talmud in Tractate Brachot (7a) discusses this issue and resolves it in the following way:
Behold one verse says: 'He delivers the sins of the fathers upon the children' (Ex. 34:7) and yet another says: 'And the children shall not die on account of their fathers' (Deut. 24:16). These verses apparently contradict one another, but they can be reconciled by saying that there is no difficulty: one verse is talking about when the children are continuing the evil ways of their parents and the other is referring to when they are not maintaining the evil ways of their parents.
So, according to the Talmud, the verse that is troubling you is referring specifically to a scenario where the children or grandchildren are continuing in their parents' evil ways. In the Book of Samuel II (21:1-11) there is an example of this, which, at first glance, seems very troubling.