WASHINGTON—A federal judge ruled Monday that the National Security Agency's collection of phone records "almost certainly" violates the Constitution, setting up a larger legal battle over long-secret counterterrorism programs.

U.S. District Judge Richard Leon's sharply worded opinion labeled as "almost Orwellian" the NSA's bulk phone-surveillance program, one of several shots the judge took at the spying and its legal justifications.

The ruling, in U.S. District Court in Washington, D.C., will have little immediate legal effect because the judge stayed the opinion until an expected government appeal is heard. But it likely propels the matter to higher courts and should give new momentum to efforts in Congress to rein in such surveillance. Bulk collection of phone records was first authorized by the Patriot Act, passed by Congress after the 2001 terror attacks, and then was placed under the supervision of a secret foreign intelligence court in 2006.

Sen. Patrick Leahy (D., Vt.), chairman of the Senate Judiciary Committee and a leading advocate of surveillance changes, hailed the ruling, as did American Civil Liberties Union attorney Jameel Jaffer, who called it a "carefully reasoned decision."

But backers of the NSA's efforts said Judge Leon advocated standards for surveillance that would be difficult if not impossible to meet. Stewart Baker, a former official for the Department of Homeland Security, called the judge's ruling "a remarkably tone-deaf approach to a program that was started because we failed to identify some of the 9/11 hijackers."