Incorrect Postgres Sequence Identified For ID Column

Over the past few months we’ve run into an unexpected snag in which it appears that when saving new records, a non-existent sequence is identified as the sequence to use to generate the new record’s ID. It appears to be irregular when it occurs, as we can sometimes go for weeks at a time without it happening but whenever it does, the only resolution we’ve been able to identify is to restart our application.

We have only observed this happening with a table that had been renamed and it’s primary key definition still references the original sequence name that was created. We’ve hopped onto the database when this error has cropped up and the table definition seems intact (the sequence referenced by the id column still exists) and after an application restart everything behaves as expected.

Create table SQL & The rename that happened:

CREATE TABLE handlers (
  id BIGSERIAL PRIMARY KEY,
  handlerQuantity NUMERIC NOT NULL
);
ALTER TABLE handlers RENAME TO handlerDefinitions;

Postgres Table:

postgres=# \d handlerdefinitions
                                      Table "public.handlerdefinitions"
        Column        |          Type          | Collation | Nullable |              Default
----------------------+------------------------+-----------+----------+------------------------------------
 id                   | bigint                 |           | not null | nextval('handlers_id_seq'::regclass)
 handlerquantity      | numeric                |           | not null |

Java Model:

@Entity
@Table(name="HandlerDefinitions")
public class HandlerDefinition {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    private Integer handlerQuantity;
}

Error message:

ERROR: relation "handlerdefinitions_id_seq" does not exist
  Position: 16

After a restart, we’ll go back to creating new records successfully until some precondition happens that we haven’t been able to identify at which point it always start trying to use the above sequence that does not exist.