Implement an optimized pagination algorithm in Python or JavaScript for handling millions of records.