To do something in the nick of time is to succeed at the last possible moment — arriving just before a deadline, making a catch just before something falls, or saying something at exactly the moment it needs to be said. There is no margin; a moment later would have been too late.
In its earlier meaning, a 'nick' was a precise notch cut into a surface, particularly into a tally stick — a wooden rod used to record scores, debts, or time. A nick indicated an exact point, not a range. To act 'in the nick' was to act at the precise mark, not approximately. The 'of time' was added for clarity, making the target of that precision explicit.
The phrase is found in English texts from the 16th century. Earlier versions used simply 'in the nick' without 'of time.' The fuller form 'in the very nick of time' appears in the 17th century and the shortened modern form was established by the 18th century. Its theatrical use became common — plays and later films used the device of rescue in the nick of time so often it became a recognised narrative structure.
Tally sticks were used to record many things: quantities of goods, amounts owed, and scores in games. A nick on the stick marked a precise point. Keepers of time would also use notched sticks to mark hours or appointments, making 'in the nick' a natural phrase for hitting an exact moment.
In modern English, 'nick' more often means a small cut or scratch, or informally means to steal (British English) or the police station. The sense of a precise point survives mainly in this phrase.