Germany's highest court has placed restrictions on an anti-terrorism law which makes telecom companies store private data for six months.
The ruling is the latest of several to go against the government
The Federal Constitutional Court in Karlsruhe ruled that data may still be kept but can only be accessed during investigations into serious crime.
Security services can use the law to obtain information on e-mails and the length and origin of phone calls.
The measure was strongly opposed by civil liberties groups.
Wednesday's ruling results from a class-action suit by 30,000 people.
Opposition parties, including the Free Democrats and the Greens had also voiced objections to the law.
Claudia Roth from the Greens said the government should "stop crossing constitutional limits on citizen rights".
The verdict was also welcomed by the country's independent privacy commissioner, Peter Schaar.
The measure was brought in following a European Union directive requiring telecom companies to keep a record of the time and location of phone calls.
It was also a response to the discovery of a number of alleged terrorism plots in Germany in recent years.
The federal justice ministry played down the significance of the ruling, and stressed that it still allowed the storage of data.
In a statement, the ministry said Germany remained in compliance with the EU directive.
The court's decision is the latest in a series to have gone against laws, brought in by Chancellor Angela Merkel's government, which harness electronic data in the fight against terrorism.
Last month, the court restricted the right of the security services to spy on the computers of suspected criminals and terrorists.
It found that "cyber spying" - which involves sending software in an e-mail to spy on a suspect's computer hard drive - violated the right to privacy.
The technique, the court ruled, could only be used in exceptional cases.