WASHINGTON — Rod J. Rosenstein, the deputy attorney general, said Monday that he would leave the Justice Department in mid-May, bringing to a close a turbulent two-year tenure that was overshadowed by the special counsel’s investigation into Russia’s efforts to sway the 2016 election in favor of President Trump.

“As I submit my resignation effective on May 11, I am grateful to you for the opportunity to serve,” Mr. Rosenstein wrote in a resignation letter to Mr. Trump. Despite a stormy relationship with the president, he praised Mr. Trump in the letter, thanking him for “the courtesy and humor” he displayed in their conversations together and for championing “patriotism, unity, safety, education and prosperity” in his inaugural address.

Department officials close to Mr. Rosenstein had previously signaled that he would leave after the completion of the report by the special counsel, Robert S. Mueller III, which was made public this month. The investigation had thrust him into a political maelstrom, challenging his reputation as a principled Republican lawyer with a distaste for politics that had been honed over 30 years as a federal prosecutor and United States attorney.

He responded by trying to thread a needle, striving to preserve the rule of law and protect one of the department’s most important investigations while publicly praising a president who he knew was determined to undermine both. It meant Mr. Rosenstein often disappointed critics on the left and the right.