When. At the end of a sitting, before standing up to leave. Any sitting: a meeting, a long meal with friends, a car journey, a group chat that has gone on for hours. It is said once, quietly, as the gathering breaks up.
The words. Four movements in one sentence, and each is a different act. Subhanaka — declaring Allah free of every fault. Wa bihamdik — and with praise of You, joined to it by the conjunction so that the negation and the praise arrive together. Ash-hadu an la ilaha illa ant — a testimony, the verb of a witness giving evidence, not of a person stating an opinion. Astaghfiruka wa atubu ilayk — asking pardon, then tawbah, whose root means to return: pardon is requested and then a direction of travel is named.
Why a gathering needs it. Kaffarah comes from a root meaning to cover. Company loosens the tongue: the exaggeration, the joke at someone's expense, the name mentioned that should not have been. Most of it is not remembered by the evening, which is exactly the problem the supplication addresses — it is said without an inventory, over whatever passed.
Not only after bad gatherings. It is said after a lesson, a good conversation, a gathering of remembrance. A person who says it only when he feels he has misbehaved has turned it into an alarm; in practice it is a closing formula, said the way a door is shut.
A note on length. It is short by design. A sitting ends when people stand, and anything longer would not survive the moment.