The custom behind Shalom Aleichem rests on a passage of the Talmud, tractate Shabbat 119b, which teaches that two ministering angels accompany a person home from the synagogue on the eve of the Sabbath, one good and one evil. If the angels find the lamps lit, the table set and the couch spread, the good angel says, may it be thus another Sabbath, and the evil angel is compelled to answer amen; if they find the house in disorder, the roles reverse.
The hymn turns that teaching into a welcome. Its four stanzas greet the ministering angels, the angels of the Most High, from the King of kings of kings, the Holy One blessed be He, then invite them, come in peace, ask of them, bless me with peace, and dismiss them, go in peace. The text appears in print in the early seventeenth century, unsigned, among the Sabbath customs that spread outward from the kabbalistic revival of Safed, and its rhythmically repeating structure, each stanza identical except for its opening verb, made it instantly memorable and singable by children, which is much of why it conquered the Jewish home. It is sung on Friday night after returning from synagogue and before the sanctification over wine, the household pausing at its own threshold to acknowledge invisible guests.