Pupils and teachers inside the Islamic study centre in downtown Kuala Lumpur screamed for help as helpless neighbours looked on.
Many of the bodies of the victims -- who included 22 boys aged between 13 and 17 -- were found piled on top of one another, indicating there may have been a stampede as the students sought to escape the blaze which erupted before dawn.
Firefighters rushed to the scene and the fire was out within an hour but it wreaked terrible devastation. Pictures in local media showed ash-covered, fire-blackened beds in the students' sleeping quarters.
"I could hear screaming, I thought there were people fighting. I opened the window to my house and I could see the school on fire -- they cried for help but I couldn't do anything."
More From This Section
By the time firefighters arrived at the Darul Quran Ittifaqiyah religious school in the heart of the capital, "the screams had stopped", she added.
Federal Territories Minister Tengku Adnan Tengku Mansor said the children, who were boarders at the school, were "desperately trying to escape the flames" but metal security grilles covering the windows of their dormitory prevented them.
Khirudin Drahman, director of Kuala Lumpur's fire and rescue department, told AFP it was one of the country's worst fire tragedies in 20 years.
Fire officials said they suspected the blaze was caused by an electrical short circuit, or a mosquito repelling device.
Officials initially said 23 students and two teachers were killed in the blaze. Police later revised down the death toll to 22 students and two teachers.
Six children were also in critical condition in hospital. Only a handful escaped unhurt.
The schools, which operate under the purview of religious authorities rather than the education department, have faced mounting criticism in recent years as many operate illegally and are seen as unsafe.
They have been under heightened scrutiny since an 11- year-old boy died after allegedly being beaten last year at one of the institutions in the southern state of Johor.
The latest tragedy was "the consequence of the absence of enforcement, and the failure to abide by rules and regulations by the operators of the religious school", said Chandra Muzaffar, a political scientist who promotes Islamic reform.
Religious schools are not "above the law. One should close down schools which do not abide by the rules", he added.
More than 60 percent of Malaysia's population of about 30 million are Muslim, and the country is also home to substantial ethnic Chinese and Indian minorities.
In October last year, six people died in a blaze that swept through the intensive care unit of a major hospital in Johor.