Create unique alphanumeric ID on wp_insert_post

See here the working version

// function to save the randomString as custom field value
function generate_AlphanumericID( $post_id ) {

    $postTypes = array('profile', 'article');
    $postType = get_post_type( $post_id );

    if (in_array( $postType, $postTypes ) ) {


        $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ-_~'!,";

        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < 11; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

         /**
         * Now check here if the string is in the database
         */
        $args = array(
        'post_type'     =>  array(
                $postTypes 
            ),
        'meta_query'    =>  array(
            array(
                'meta_key'  =>  '_alphanumeric_id'
            )
        )
        );
        $posts = new WP_Query( $args );


        $meta_values="";
        if( $posts->have_posts() ) {
          while( $posts->have_posts() ) {
            $posts->the_post();

            $meta_values[] = get_post_meta( get_the_ID(), '_alphanumeric_id', true );
          }
        } 
        wp_reset_postdata();


        if (in_array( $randomString, $meta_values )) {
            // "Match found"
            return generate_AlphanumericID;

        }  else {
            // "Match not found"
            add_post_meta($post_id, '_alphanumeric_id', $randomString);
            return $randomString;
        }

    }

}
add_action('draft_to_publish', 'generate_AlphanumericID', 10, 3);

Note:

To use this key as permalink tag I recommend you this https://github.com/athlan/wordpress-custom-fields-permalink-plugin