I fixed the problem and I think it was using $node variable in a page layout template. When I replaced the $node.node_id variable in the first line with $module_result.content_info.node_id everything works fine.
Is this because $node is only available in a content view? Why would it work when not cached and only have problems when executing a cached template?